[英]Write list of int or float to CSV
I'm stuck with this problem. 我陷入了这个问题。 I followed many examples of code found here on SO an on official documentation pages, but what I get is:
我在官方文档页面上跟踪了SO上的许多代码示例,但得到的是:
Python 3.7.0 (default, Aug 22 2018, 20:50:05)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import csv
>>>
>>> float_list = [1.13, 0.25, 3.28]
>>>
>>> with open('some.csv', "wb") as file:
... writer = csv.writer(file, delimiter=',')
... writer.writerow(float_list)
...
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
TypeError: a bytes-like object is required, not 'str'
>>>
Same thing also with: 同样的事情也与:
int_list=[1,2,3]
Some suggestions? 有什么建议吗?
The "wb" used in your code means that you are writing to the file (using w ) and that you are writing in binary mode (using b ). 代码中使用的“ wb”表示您正在写入文件(使用w ),并且正在以二进制模式写入(使用b )。
For this reason you get the error that you are seeing, you told the writer to expect bytes but then you are sending strings. 出于这个原因,您得到了所看到的错误,告诉编写者期望字节,但是随后您正在发送字符串。
Please change: 请更换:
with open('some.csv', "wb") as file:
To: 至:
with open('some.csv', "w") as file:
Here's more technical details: 以下是更多技术细节:
On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'.
在Windows上,附加到模式的'b'以二进制模式打开文件,因此也有'rb','wb'和'r + b'之类的模式。 Python on Windows makes a distinction between text and binary files;
Windows上的Python区分文本文件和二进制文件。 the end-of-line characters in text files are automatically altered slightly when data is read or written.
当读取或写入数据时,文本文件中的行尾字符会自动更改。 This behind-the-scenes modification to file data is fine for ASCII text files, but it'll corrupt binary data like that in JPEG or EXE files.
对于ASCII文本文件来说,对文件数据进行这种幕后修改是可以的,但它会破坏JPEG或EXE文件中的二进制数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.