【发布时间】:2013-04-22 16:21:51
【问题描述】:
在 Windows 8 上使用 Python 3.3,写入 CSV 文件时,我收到错误 TypeError: 'str' does not support the buffer interface 和 "wb" 标志被使用。但是,当仅使用 "w" 标志时,我没有收到任何错误,但每一行都由一个空白行分隔!
问题写作
代码
test_file_object = csv.reader( open("./files/test.csv", 'r') )
next(test_file_object )
with open("./files/forest.csv", 'wb') as myfile:
open_file_object = csv.writer( open("./files/forest.csv", 'wb') )
i = 0
for row in test_file_object:
row.insert(0, output[i].astype(np.uint8))
open_file_object.writerow(row)
i += 1
错误
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-121-8cbb94f602a8> in <module>()
8 for row in test_file_object:
9 row.insert(0, output[i].astype(np.uint8))
---> 10 open_file_object.writerow(row)
11 i += 1
TypeError: 'str' does not support the buffer interface
问题解读
阅读时,我似乎无法使用"rb" 标志,因此在尝试忽略第一行(标题)时会出现错误iterator should return strings, not bytes。
代码
csv_file_object = csv.reader(open('files/train.csv', 'rb'))
header = next(csv_file_object)
train_data = []
for row in csv_file_object:
train_data.append(row)
train_data = np.array(train_data)
错误
Error Traceback (most recent call last)
<ipython-input-10-8b13d1956432> in <module>()
1 csv_file_object = csv.reader(open('files/train.csv', 'rb'))
----> 2 header = next(csv_file_object)
3 train_data = []
4 for row in csv_file_object:
5 train_data.append(row)
Error: iterator should return strings, not bytes (did you open the file in text mode?)
【问题讨论】:
-
我认为这是 this question 的副本,等等。在 Python 3 中打开 csv 文件的方式有所不同;查看
reader和writerhere 的打开。
标签: python csv python-3.x