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

hos*_*255 3 python ansi utf-8

我在 Windows 10 环境中使用 python 3.5.2 解释器。

\n\n

我根据 Google 的 Python 课程输入了以下几行:

\n\n
>>> import sys,os,codecs\n>>> f=codecs.open(\'foo.txt\',\'rU\',\'utf-8\')\n>>> for line in f:\n...    f.write(\'\xc2\xa3 $\')\n...\nTraceback (most recent call last):\n  File "<stdin>", line 2, in <module>\n  File "C:\\Users\\rschostag\\AppData\\Local\\Programs\\Python\\Python35-32\\lib\\codecs.py", line 718, in write\n    return self.writer.write(data)\n  File "C:\\Users\\rschostag\\AppData\\Local\\Programs\\Python\\Python35-32\\lib\\codecs.py", line 377, in write\n    self.stream.write(data)\nio.UnsupportedOperation: writ\n
Run Code Online (Sandbox Code Playgroud)\n\n

foo.txt 的内容当前为:

\n\n
string1\nstring2\n
Run Code Online (Sandbox Code Playgroud)\n\n

foo.txt,根据记事本中的“另存为...”,是 ANSI。是否需要将其转换为 UTF-8 才能将 UTF-8 字符写入文件?

\n

syt*_*ech 6

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

rU指定读数

f=codecs.open('foo.txt','rU','utf-8')
Run Code Online (Sandbox Code Playgroud)

打开进行写入:

f=codecs.open('foo.txt','w','utf-8')
Run Code Online (Sandbox Code Playgroud)