user5768866
user5768866

Reputation:

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]])

Upvotes: 0

Views: 87

Answers (2)

neehari
neehari

Reputation: 2612

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)

Upvotes: 0

hiro protagonist
hiro protagonist

Reputation: 46839

you open your file in 'binary' mode instead of 'text' mode:

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

should work.

Upvotes: 4

Related Questions