在写入文件之前删除文件的内容(在 Python 中)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41915140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:51:27  来源:igfitidea点击:

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

pythonoverwritefile-writing

提问by Tare Gaskin

I'm trying my hand at this rosalind problemand 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.

我正在尝试解决这个 rosalind 问题但遇到了一个问题。我相信我的代码中的所有内容都是正确的,但显然不是因为它没有按预期运行。我想删除文件的内容,然后向该文件写入一些文本。程序写入我想要的文本,但它不会首先删除初始内容。

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?

如何在python脚本中写入文件之前删除文件的内容?

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

但我的问题仍然存在。我究竟做错了什么?

回答by Charles Duffy

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

truncate()当前位置截断。根据其文档,重点补充说:

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.

在 a 之后read(),当前位置是文件的结尾。如果要使用相同的文件句柄进行截断和重写,则需要执行 aseek(0)以返回到开头。

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

(您也可以通过raw.truncate(0),但这会使指针 - 以及未来写入的位置 - 留在文件开头以外的位置,当您开始在该位置写入文件时,会使文件稀疏) .

回答by Ofer Arial

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

如果你想完全覆盖文件中的旧数据,你应该使用另一个mode打开文件。

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 writemode.This way, you will not append your text to the file, you'll just write only your data to it.

然后使用模式打开它write。这样,您不会将文本附加到文件中,您只需将数据写入其中。

Read about mode files here.

在此处阅读有关模式文件的信息