Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

deleting words from a file and saving the rest to the same file

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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"
delete_list = ["vul"]

with fileinput.input(files=filepath, inplace=True) as file:
    for line in file:
        words = [word for word in line.split() if word not in delete_list]
        print(' '.join(words))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading