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

时间:2017-01-28 21:40:57

标签: python overwrite file-writing

我正试着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?

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

2 个答案:

答案 0 :(得分:12)

truncate()截断当前位置。根据其文件,强调增加了:

  

将流大小调整为给定大小,单位为(如果未指定大小,则为当前位置)

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),但这会将指针 - 以及将来写入的位置 - 留在文件开头以外的位置,使你的文件稀疏开始在那个位置写信。)

答案 1 :(得分:4)

如果您想完全覆盖文件中的旧数据,则应使用其他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

相关问题