【问题标题】:How to fix "io.UnsupportedOperation: File not open for writing" Error? [duplicate]如何修复“io.UnsupportedOperation: File not open for writing”错误? [复制]
【发布时间】: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 中打开了?

标签: python file


【解决方案1】:

以 rw+ 追加模式打开文件,以便正确截断文件

while True:
file = open("test.txt","rw+")
file.truncate()
x = file.read()
x = x.split("\n")
print(x[0])
print(x[1])
time.sleep(3)

【讨论】:

  • 当我完成后,我得到了这个错误“ValueError: must have just one of create/read/write/append mode”
猜你喜欢
  • 2012-03-30
  • 2019-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多