首页 文章

编写UTF-8字符时出现Python错误“io.UnsupportedOperation:write”

提问于
浏览
-1

我在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 回答

  • 3

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

    rU 指定读数

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

    打开写作:

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

相关问题