2016-07-12 12 views
-1

Windows 10環境でPython 3.5.2インタプリタを使用しています。UTF-8文字を書くときのPythonエラー "io.UnsupportedOperation:write"

私はGoogleのPythonのコースに応じて、次の行に入力:foo.txtの内容は現在

>>> 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 

を:

string1 
string2 

foo.txtの、名前を付けて保存によると...メモ帳で、ANSIです。 UTF-8文字をファイルに書き込むには、これをUTF-8に変換する必要がありますか?

+3

あなたが読書のためのファイルを開いて、あなたがそれに書き込むことはできませんなぜ今、あなたは知らないのですか? – Matthias

答えて

0

ファイルは、書き込み用ではなく、読み込み用に開いています。したがって、サポートされていない操作です。読み込み用に開いたファイルに書き込むことはできません。

rUは書き込みのためにオープンする

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

を読ん指定:

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

それを明確にしていただきありがとうございます。 –

関連する問題