python - How to save each string to a separate file? -
i have folder including files open , read, extract persian words them separately , join each set of words make sentence. want save each sentence separate .txt file. problem last sentence saved in files. how can fix it?
import os import codecs ###opening files folder in directory matches=[] root, dirs, files in os.walk("c:\\users\\maryam\\desktop\\new folder"): file in files: if file.endswith(".pts"): matches.append(os.path.join(root, file)) print(matches) print(len(matches)) ###reading files f in matches: codecs.open(f, "r", "utf-8") fp: text=fp.read().split('\n') #print(text) #print (len(text)) ###converts 1 string strings line in text: line_list=line.split() #print (line_list) ###extracting persian words , removing parantheses list_persian_letters=['ا','آ', 'ب','پ','ت','ث','ج','چ','ح','خ','د','ذ','ر','ز','ژ','س','ش','ص','ض','ط','ظ','ع','غ','ف','ق','ک','گ','ل','م','ن','و','ه','ی','.','؟','،',':','!'] output_words = [word word in line_list if (word[0] in list_persian_letters)] output=[s.replace(')', '') s in output_words] #print (output) ###joining words as sentence sentence=' '.join(output) ###saving each sentence in separate file in range(1,16): codecs.open ("f:\\new folder\\output%i.txt" %i, "w","utf-8") text_file: text_file.writelines(sentence)
all files overwritten in each loop iteration. see result of last iteration.
change outer loop to:
for i, f in enumerate(matches):
and
for j, line in enumerate(text):
and rid of 1..16 loop:
for in range(1,16):
and modify:
with codecs.open ("f:\\new folder\\output%i_%i.txt" % (i,j), "w","utf-8") text_file:
i hope change code wanted.
Comments
Post a Comment