Python3.1 的 csv 模块

1 投票
1 回答
956 浏览
提问于 2025-04-16 07:56

我在使用Python2.x时用的是以下代码:

import csv
f = open('test.csv', 'wb')
writer = csv.writer(f)
writer.writerow((fpath, md5sum, size)) # <str>, <str>, <int>

这个在Python2.x里运行得很好,没有任何问题。不过,当我在Python3里运行这个代码时,就出现了一个类型错误(TypeError)。

writer.writerow((fpath, md5sum, size))
TypeError: write() argument 1 must be bytes or buffer, not str

当然,如果我以非二进制模式打开文件并写入数据,那是可以解决这个问题的,但我喜欢Python3对Unicode的处理方式。我希望在写入文件之前特别编码数据,而在读取时再解码。

我该怎么解决这个问题呢?

1 个回答

6
f = open('test.csv', 'w', encoding='utf-8', newline='')

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。

撰写回答