[英]How can I create a file with utf-8 in Python?
我使用open('test.txt', 'w')
創建一個新文件,它的字符集是binary 。
>>> open('test.txt', 'w')
<open file 'test.txt', mode 'w' at 0x7f6b973704b0>
$ file -i test.txt.txt
test2.txt: inode/x-empty; charset=binary
使用模塊codecs
分配具有指定字符集(例如utf-8
)的文件。 但是,字符集仍然是binary 。
>>> codecs.open("test.txt", 'w', encoding='utf-8')
<open file 'test.txt', mode 'wb' at 0x7f6b97370540>
$ file -i test.txt
test.txt: inode/x-empty; charset=binary
我給test.txt
寫了一些東西,字符集是us-ascii 。
>>> fp. write ("wwwwwwwwwww")
>>> fp.close()
$ file -i test.txt
test.txt: text/plain; charset=us-ascii
好的,現在,我寫了一些特殊字符(比如Arènes
)。 然而,
>>> fp = codecs.open("test.txt", 'w', encoding='utf-8')
>>> fp.write("Arènes")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/codecs.py", line 688, in write
return self.writer.write(data)
File "/usr/lib/python2.7/codecs.py", line 351, in write
data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2: ordinal not in range(128)
更具體地說,我想將查詢結果(使用python-mysqldb
)保存到一個文件中。 關鍵源代碼如下:
cur.execute("SELECT * FROM agency")
# Write to a file
with open('test.txt', 'w') as fp :
for row in cur.fetchall() :
s = '\t'.join(str(item) for item in row)
fp.write(s + '\n')
現在, test.txt
的字符集是iso-8859-1 (一些法語字符,例如Arènes
)。
因此,我使用codecs.open('test.txt', 'w', encoding='utf-8')
創建一個文件。 但是,遇到以下錯誤:
Traceback (most recent call last):
File "./overlap_intervals.py", line 26, in <module>
fp.write(s + '\n')
File "/usr/lib/python2.7/codecs.py", line 688, in write
return self.writer.write(data)
File "/usr/lib/python2.7/codecs.py", line 351, in write
data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 21: ordinal not in range(128)
如何在 Python 中使用 utf-8 創建文件?
空文件始終是二進制文件。
$ touch /tmp/foo
$ file -i /tmp/foo
/tmp/foo: inode/x-empty; charset=binary
把東西放進去,一切都很好。
$ cat > /tmp/foo
Rübe
Möhre
Mähne
$ file -i /tmp/foo
/tmp/foo: text/plain; charset=utf-8
Python 將執行與cat
相同的操作。
with open("/tmp/foo", "w") as f:
f.write("Rübe\n")
核實:
$ cat /tmp/foo
Rübe
$ file -i /tmp/foo
/tmp/foo: text/plain; charset=utf-8
編輯:
使用 Python 2.7,您必須對 Unicode 字符串進行編碼。
with open("/tmp/foo", "w") as f:
f.write(u"Rübe\n".encode("UTF-8"))
在 Python 3 中,您還應該指定 write() 的編碼:
with open("filepath", "w", encoding="utf-8") as f:
f.write("Arènes")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.