简体   繁体   中英

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:

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:

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. Here is some helpful documentation.

Python distinguishes between binary and text I/O. Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding. 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.

You could also use pandas to_csv :

import pandas as pd

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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