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

标签 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?

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

最佳答案

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/

相关文章:

python - 属性错误 : 'module' object has no attribute 'TimeSeries' after python Validation. py

python - Anaconda 默认目录

R:避免意外覆盖变量

php - Firebase Firestore 添加数据而不覆盖

json - 如何在写入文件之前删除文件的内容?

python - 具有自定义插槽的 PyQt5 设计器

c++ - 可变参数模板和覆盖

python - 如何将抓取的数据写入csv格式?

python - 使用 "with open() as file"方法,如何多次写入?

python - 使用 ipython 对 dl.open() 的权限被拒绝,但不使用 python