Delete the contents of a file before writing to it (in Python)?

Tare Gaskin picture Tare Gaskin · Jan 28, 2017 · Viewed 38.1k times · Source

I'm trying my hand at this rosalind problem and am running into an issue. I believe everything in my code is correct but it obviously isn't as it's not running as intended. i want to delete the contents of the file and then write some text to that file. The program writes the text that I want it to, but it doesn't first delete the initial contents.

def ini5(file):
raw = open(file, "r+")
raw2 = (raw.read()).split("\n")
clean = raw2[1::2]
raw.truncate()
for line in clean:
    raw.write(line)
    print(line)

I've seen:

How to delete the contents of a file before writing into it in a python script?

But my problem still persists. What am I doing wrong?

Answer

Charles Duffy picture Charles Duffy · Jan 28, 2017

truncate() truncates at the current position. Per its documentation, emphasis added:

Resize the stream to the given size in bytes (or the current position if size is not specified).

After a read(), the current position is the end of the file. If you want to truncate and rewrite with that same file handle, you need to perform a seek(0) to move back to the beginning.

Thus:

raw = open(file, "r+")
contents = raw.read().split("\n")
raw.seek(0)                        # <- This is the missing piece
raw.truncate()
raw.write('New contents\n')

(You could also have passed raw.truncate(0), but this would have left the pointer -- and thus the location for future writes -- at a position other than the start of the file, making your file sparse when you started writing to it at that position).