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

浪尽此生 提交于 2020-07-15 05:07:51

问题


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?


回答1:


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).




回答2:


If you want to completley overwrite the old data in the file, you should use another mode to open the file.

It should be:

raw = open(file, "w") # or "wb"

To resolve your problem, First read the file's contents:

with open(file, "r") as f: # or "rb"
    file_data = f.read()
# And then:
raw = open(file, "w")

And then open it using the write mode.This way, you will not append your text to the file, you'll just write only your data to it.

Read about mode files here.



来源:https://stackoverflow.com/questions/41915140/delete-the-contents-of-a-file-before-writing-to-it-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!