简体   繁体   中英

python `csv` library. writerows(['a', 'b']) is putting 2 rows into the csv

I just tried to put single row into the csv file.

with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(['a', 'b')

Expected CSV Output

[a, b]

Actual CSV Output

[a]
[b]

writerows() writes each element in the input iterable as a new row

If you want a single row "a, b" add an additional level of nesting to your list:

with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows([['a', 'b']])

Additionally if you only want to write a single row you can do what TeeKea suggests in his answer and use writerow() ,

writerows(iterable) essentially functions as:

for item in iterable:
    writer.writerow(item)

First, if you supply ['a', 'b'] to writerows , you should get this error:

_csv.Error: iterable expected, not int

Second, if you open the file with the wb mode, you should also be getting the following error when you write a list to it:

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

Therefore, to write the list ['a', 'b'] to a csv file, you would probably need to open the file in a w mode and use writerow instead of writerows , as follows:

with open("output.csv", "w") as f:
    writer = csv.writer(f)
    writer.writerow(['a', 'b'])

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