0

I followed this subject here because I want to remove the <br /> that are in my output text file.

So my code is the following one :

def file_cleaner(video_id):
    with open('comments_'+video_id+'.txt', 'r') as infile, open('comments_'+video_id+'.txt', 'w') as outfile:
        temp = infile.read().replace("<br />", "")
        outfile.write(temp)  

If I remove this function call my file has content, but after I call this function my file is empty. Where did I do something wrong ?

J.erome
  • 688
  • 7
  • 26
  • Opening a file in `w` mode empties it first. – Barmar Mar 19 '21 at 20:28
  • 1
    You cannot `open()` the same file twice. Also `'w'` truncates the file when it opens it. – gen_Eric Mar 19 '21 at 20:28
  • so what should I change ? – J.erome Mar 19 '21 at 20:29
  • 1
    @J.erome Try opening a _different_ file as `outfile`. Otherwise, you'll have to open the file _once_ for both reading _and_ writing `'r+'`. Read the file data, change it, then write the new data back (making sure to "rewind" the file first). – gen_Eric Mar 19 '21 at 20:30
  • https://stackoverflow.com/questions/13089234/replacing-text-in-a-file-with-python I guess it's my solution – J.erome Mar 19 '21 at 20:30

1 Answers1

3

Opening a file in w mode truncates the file first. So there's nothing to read from the file.

Read the file first, then open it for writing.

def file_cleaner(video_id):
    with open('comments_'+video_id+'.txt', 'r') as infile:
        temp = infile.read().replace("<br />", "")
    with open('comments_'+video_id+'.txt', 'w') as outfile:
        outfile.write(temp)
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    ...with the caveat that the file can end up corrupt if the program exits partway through the `outfile.write()` operation, hence why there are a lot of existing Q&A entries about how to _atomically_ update a file's contents in Python. – Charles Duffy Mar 19 '21 at 20:33