Reputation: 517
I have a the text of a book in txt format.
If a word is contained in specific_words_dict
dictionary, I would like to replace that word with word_1 (cat
with cat_1)
.
I wrote this code, but it doesn't replace the word in the file.
for filename in os.listdir(path):
with open(path+"/"+filename,'r+') as textfile:
for line in textfile:
for word in line.split():
if(specific_words_dict.get(word) is not None):
textfile.write(line.replace(word,word+"_1"))
What am I doing wrong?
Upvotes: 0
Views: 1209
Reputation: 12157
Don't read and write to a file at the same time. It won't end well. I think at the moment you're appending to the file (so all your new lines are going to the end).
If the file is not too big (it probably won't be), I'd read the whole thing into ram. Then you can edit the list of lines, before rewriting the whole file. Not efficient, but simple, and it works.
for filename in os.listdir(path):
with open(os.path.join(path, filename)) as fr:
lines = fr.read().splitlines()
for index, line in enumerate(lines):
for word in line.split():
if specific_words_dict.get(word) is not None:
lines[index] = line.replace(word, word + "_1")
with open(os.path.join(path, filename), 'w') as fw:
fw.writelines(lines)
Upvotes: 3
Reputation: 114
Write in other file In addition, you can check if your word is in uppercase or lower case in your dict or in your files. It is maybe why "replace" doesn't work.
for filename in os.listdir(path):
with open(path+"/"+filename,'r+') as textfile, open(path+"/new_"+filename,'w') as textfile_new:
for line in textfile:
new_line = line
for word in line.split():
if(specific_words_dict.get(word) is not None):
new_line = new_line.replace(word,word+"_1")
textfile_new.write(new_line)
Upvotes: 2