【问题标题】:How can I create a file with utf-8 in Python?如何在 Python 中使用 utf-8 创建文件?
【发布时间】:2015-06-18 10:02:16
【问题描述】:

我使用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)的文件。但是,字符集仍然是二进制

>>> 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 创建文件?

【问题讨论】:

  • 您的文件为空。你期待什么?
  • 尝试添加一些条目并检查。
  • @Tichodroma @Anand S Kumar,我在这个文件中写了一些东西。但是,字符集是 us-ascii,而不是 utf-8
  • 写一些实际上需要 UTF-8 的 Unicode 字符。
  • ASCII 对于wwwwwwwwwww 来说已经足够了,使用类似äöü€ÄÖÜ 的字符串作为字符串。请参阅下面如何将 UTF8 编码的 Unicode 写入文件的答案。

标签: python utf-8 character-encoding


【解决方案1】:

空文件始终是二进制文件。

$ 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"))

【讨论】:

  • 出现错误:UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128) while running fp.write("Rübe")
  • 使用哪个 Python 版本?
  • Python 2.7.6。是不是我安装python-mysqldb后没有重启机器的原因?
【解决方案2】:

在 Python 3 中,您还应该指定 write() 的编码:

with open("filepath", "w", encoding="utf-8") as f:
    f.write("Arènes")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-23
    • 2013-05-12
    相关资源
    最近更新 更多