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

2024-05-13 07:41:52 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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)

我见过:

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

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


Tags: 文件代码in文本程序clean内容raw
2条回答

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

应该是:

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

要解决问题,请先读取文件的内容:

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

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

阅读模式文件here

truncate()在当前位置处截断。在其文件中,强调指出:

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

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

因此:

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

(您也可以传递raw.truncate(0),但这会将指针(以及以后写入的位置)留在文件开头以外的位置,当您在该位置开始写入文件时使文件变得稀疏)。

相关问题 更多 >