我在 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\nRun Code Online (Sandbox Code Playgroud)\n\nfoo.txt 的内容当前为:
\n\nstring1\nstring2\nRun Code Online (Sandbox Code Playgroud)\n\nfoo.txt,根据记事本中的“另存为...”,是 ANSI。是否需要将其转换为 UTF-8 才能将 UTF-8 字符写入文件?
\n您打开文件以供读取,而不是写入。因此,操作不受支持。您无法写入打开以供读取的文件。
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)
| 归档时间: |
|
| 查看次数: |
17639 次 |
| 最近记录: |