我正在尝试 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?
但我的问题仍然存在。我做错了什么?
最佳答案
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)
,但这会使指针——以及 future 写入的位置——留在除开始之外的位置文件,当你开始在那个位置写入文件时,使你的文件变得稀疏)。
关于python - 在写入文件之前删除文件的内容(在 Python 中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41915140/