我在Windows 10环境中使用python 3.5.2解释器 .
我根据Google的Python课程输入了以下几行:
>>> import sys,os,codecs
>>> f=codecs.open('foo.txt','rU','utf-8')
>>> for line in f:
... f.write('£ $')
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "C:\Users\rschostag\AppData\Local\Programs\Python\Python35-32\lib\codecs.py", line 718, in write
return self.writer.write(data)
File "C:\Users\rschostag\AppData\Local\Programs\Python\Python35-32\lib\codecs.py", line 377, in write
self.stream.write(data)
io.UnsupportedOperation: writ
foo.txt的内容目前是:
string1
string2
根据记事本中的另存为,foo.txt是ANSI . 这是否需要转换为UTF-8才能将UTF-8字符写入文件?
1 回答
您打开文件进行阅读,而不是写作 . 因此,不支持的操作 . 您无法写入打开以供阅读的文件 .
rU
指定读数打开写作: