出现这个问题的是因为我要将读过的文件清空
使用下面这个方法
f.truncate()
一运行就会出现错误,下面是原来的代码:
with open("msg.json", 'r', encoding='utf8') as f:
content = f.read()
f.seek(0)
f.truncate()
print(content)
错误信息
Traceback (most recent call last):
File "D:/python/project/tujia.com/tujia_im_demo2/test_file.py", line 13, in <module>
f.truncate()
io.UnsupportedOperation: File not open for writing
这是清空文件的操作必须要有写的操作,具体可以看我的另一篇博客Python文件读写模式r,r+,w,w+,a,a+的区别
所以做修改,将 r 改为 r+ 就行
with open("msg.json", 'r+', encoding='utf8') as f:
content = f.read()
f.seek(0)
f.truncate()
print(content)
我自己再改的时候试过rb+,这会将文件以二进制读写,所有就不能有 encoding=‘utf8’ .有的话就会报错
ValueError: binary mode doesn't take an encoding argument
还有一个坑
因为我的代码是下载while True。读完文件会有一个发送的操作,发送操作之后写的清空操作。但是不起作用,文件中的内容是一直在的。
while True:
try:
with open("msg.json", 'rb+') as f:
content = f.read()
if content:
socketIO.emit('chat', json.dumps(content.decode('utf8')), path=path)
f.seek(0)
f.truncate()
except:
然后自己尝试做如下修改,将清空操作,放在文件读取后面。然后问题解决,目前没搞明白这是什么原因。
with open("msg.json", 'rb+') as f:
content = f.read()
f.seek(0)
f.truncate()
更多内容请关注我的微信公众号