io.UnsupportedOperation: File not open for writing错误解决

川长思鸟来 2021-12-09 07:03 587阅读 0赞

出现这个问题的是因为我要将读过的文件清空

使用下面这个方法

  1. f.truncate()

一运行就会出现错误,下面是原来的代码:

  1. with open("msg.json", 'r', encoding='utf8') as f:
  2. content = f.read()
  3. f.seek(0)
  4. f.truncate()
  5. print(content)

错误信息

  1. Traceback (most recent call last):
  2. File "D:/python/project/tujia.com/tujia_im_demo2/test_file.py", line 13, in <module>
  3. f.truncate()
  4. io.UnsupportedOperation: File not open for writing

这是清空文件的操作必须要有写的操作,具体可以看我的另一篇博客Python文件读写模式r,r+,w,w+,a,a+的区别

所以做修改,将 r 改为 r+ 就行

  1. with open("msg.json", 'r+', encoding='utf8') as f:
  2. content = f.read()
  3. f.seek(0)
  4. f.truncate()
  5. print(content)

我自己再改的时候试过rb+,这会将文件以二进制读写,所有就不能有 encoding=‘utf8’ .有的话就会报错

  1. ValueError: binary mode doesn't take an encoding argument

还有一个坑

因为我的代码是下载while True。读完文件会有一个发送的操作,发送操作之后写的清空操作。但是不起作用,文件中的内容是一直在的。

  1. while True:
  2. try:
  3. with open("msg.json", 'rb+') as f:
  4. content = f.read()
  5. if content:
  6. socketIO.emit('chat', json.dumps(content.decode('utf8')), path=path)
  7. f.seek(0)
  8. f.truncate()
  9. except:

然后自己尝试做如下修改,将清空操作,放在文件读取后面。然后问题解决,目前没搞明白这是什么原因。

  1. with open("msg.json", 'rb+') as f:
  2. content = f.read()
  3. f.seek(0)
  4. f.truncate()

更多内容请关注我的微信公众号

在这里插入图片描述
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,587人围观)

还没有评论,来说两句吧...

相关阅读