Problem replacing contents of file

I’m new to python and have Googled this and found many of the same solutions. I can’t get it to work, as the resulting file is always empty. I want to end up with the oldfile and newfile to have exactly the same contents.

A new file is distributed on a website approximately every week. I’d like to check the file daily to see if it (newfile) matches the previous file (oldfile) that was downloaded. I have these parts working. If the files do not match, I’m able to append the contents of new file to another file (datafile) that continues to grow indefinitely.

The problem is that I can’t get the newfile to overwrite the contents of the old file. The contents of the old file are emptied out and nothing is inserted.

location = “C:/Users/username/Downloads/Python”
datafile = location + “/” + “Main_IP.txt”
oldfile= location + “/” + “CurrentIPs.txt”
newfile = location + “/” + “IPs.txt”
f1 = open(datafile, ‘a’)
f2 = open(oldfile, ‘w+’)
f3 = open(newfile, ‘r’)

f1.write(f3.read()) ! This appends to data file OK
f2.write(f3.read()) ! The old file remains empty

I’ve tried to use the seek/write/truncate, but I can’t get that to work either. Can someone direct me as to what I’m missing? Thank you.

One problem is that here you’re not closing the file after opening it. To speed up performance, Python and the OS doesn’t immediately write things, but instead collects up writes in memory and then writes them to disk in chunks. Closing the file ensures it finishes up properly. You could call .close() manually, but the best practice is to use a with statement:

with open("path/to/file", "r") as fsrc, open("path/to/file", "w") as fdest:
    fdest.write(fsrc.read())

When you exit a with statement (even if an error occurs), it automatically closes the file. Python does also try to close the file when the object is deleted, but that’s not fully reliable.

Possibly another problem with file2 is that since you opened it in both read and write mode, reading would mean it has moved the “cursor” to the end of the file. You’ll want to .seek(0) to move back to the start.

Thank you - great to know. I’ll give this a shot.

You said you tried seeking, but you didn’t say for which file or to what point. So I’m just going to state the obvious here. This example is missing f3.seek(0) after the first f3.read(). Reading the entire contents of the file leaves the file pointer at the end of the file. Calling read() again thus returns an empty string. For example:

>>> f = open('spam.txt', 'r')
>>> f.read()
'spam\n'
>>> f.read()
''

You could also read the contents once, and reference the data as a local variable, e.g. data = f3.read(). Then write it with f1.write(data) and f2.write(data).