Python 写入 UTF-8 字符时出错 "io.UnsupportedOperation: write"

Python error "io.UnsupportedOperation: write" when writing UTF-8 Characters

我在 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 字符写入文件?

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

rU指定读数

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

打开写入:

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