I have a trivial problem
I want the words that were removed to all be uploaded to the same file where I'm making a mistake: D
infile = "tada.txt"
outfile = "tada.txt"
word = "vul"
tada=(''.join(word))
delete_list = tada
with open(infile) as fin, open(outfile, "w ") as fout:
for line in fin:
for word in delete_list:
line = line.replace(word, "")
fout.write(line)
from text
this is vul great
if there is a word vul in the file
output is
this is great
so I want the same output to be in the same file
but the problem is that the script deletes everything and the file remains empty
CodePudding user response:
You can effectively change a file "in place" by using Python's fileinput
module. Here's how it could be used to what you want (i.e. remove words from each line).
Note that unlike your code, the following will delete whole words not letters of one in each line.
import fileinput
filepath = "tada.txt"
banned = {"bfd", "vul", "wtf"} # Disallowed words.
with fileinput.input(files=filepath, inplace=True) as file:
for line in file:
words = [word for word in line.split() if word.lower() not in banned]
print(' '.join(words))