【发布时间】:2019-05-17 01:12:31
【问题描述】:
简单来说,当我尝试运行少量代码来删除文件的内容,然后将内容重写到该文件时,它会引发该错误。我正在尝试使用 CoolTerm 的文件写入从 com 端口获取温度读数,也许是因为该文件也被 CoolTerm 使用,所以我无法编辑它,但我不确定。
我尝试了多种方法来删除文件信息,例如 file.close() 等,但似乎都没有。
while True:
file = open("test.txt","r")
file.truncate()
x = file.read()
x = x.split("\n")
print(x[0])
print(x[1])
time.sleep(3)
我希望控制台输出文件的内容,但它没有。给我一个与我想要的类似结果的东西是控制台只输出文件的最后两个条目,而不是必须删除所有文件而不是重写它。
【问题讨论】:
-
您正在以
read模式打开文件。使用w+进行读写。 -
改用
with open("test.txt", "w+") as file:。 -
在
w+模式下打开文件会truncate it for you -
所以当我这样做时,它给了我一个权限错误
Traceback (most recent call last): File "<pyshell#40>", line 2, in <module> file = open("test.txt", "w+") PermissionError: [Errno 13] Permission denied: 'test.txt' -
+Boris I Get a permission Denied 错误?会不会是因为它在 CoolTerm 中打开了?