Python错误" io.UnsupportedOperation:写"写UTF-8字符时

时间:2016-07-12 19:43:25

标签: python utf-8 ansi

我在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 个答案:

答案 0 :(得分:3)

您打开文件进行阅读,而不是写作。因此,不支持的操作。您无法写入为阅读而打开的文件。

rU指定的读数

f=codecs.open('foo.txt','rU','utf-8')

开放写作:

f=codecs.open('foo.txt','w','utf-8')