-1

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

Zion Alt
  • 27
  • 7
  • What's your question exactly? Do you know why the problem is happening? (Hint: [What does `w+` do?](/a/16208298/4518341)) What research have you done? What have you tried to fix it? Please read [ask]. You can [edit] to clarify. Then once that problem is fixed, it looks like there are two more problems (`for word in delete_list` and `is great`). You might want to read [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) and [mre]. For reference, ["Can someone help me?" is not an actual question](https://meta.stackoverflow.com/q/284236/4518341) on SO. – wjandrea May 07 '22 at 17:29
  • @wjandrea ok sory I've been trying to get this new one in python so it's beyond me – Zion Alt May 07 '22 at 17:51

1 Answers1

1

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))
martineau
  • 119,623
  • 25
  • 170
  • 301