简体   繁体   English

如何将列表写入csv文件

[英]how to write a list into csv file

I tried the below code to write a list to csv file, but it always shows the error: 我尝试下面的代码将列表写入csv文件,但始终显示错误:

a bytes-like object is required, not 'str'

Below is the code: 下面是代码:

import csv
a=['a','b','c']
with open(r"result.csv",'wb') as resultFile:
    writer = csv.writer(resultFile, lineterminator='\n')
    for i in a:
        writer.writerows([[i]])

you open your file in 'binary' mode instead of 'text' mode: 您以“二进制”模式而不是“文本”模式open文件:

with open(r"result.csv",'w') as resultFile:  # instead of 'wb'

should work. 应该管用。

Like @hiro protagonist said, you are opening the file in binary mode. 就像@hiro主角所说,您正在以二进制模式打开文件。 Here is some helpful documentation. 是一些有用的文档。

Python distinguishes between binary and text I/O. Python区分二进制I / O和文本I / O。 Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding. 以二进制模式打开的文件(包括mode参数中的'b')以字节对象的形式返回内容,而无需进行任何解码。 In text mode (the default, or when 't' is included in the mode argument), the contents of the file are returned as str , the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given. 在文本模式下(默认设置,或者在mode参数中包含't'时),文件内容以str形式返回,首先使用平台相关的编码或指定的编码(如果给定的话)对字节进行解码。

You could also use pandas to_csv : 您也可以使用pandas to_csv

import pandas as pd

a = ['a', 'b', 'c']
df = pd.DataFrame(a)
df.to_csv('result.csv', header=None, index=False)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM