Using the CSV module, I export the list to the CSV file with the following two codes (sample-01/02.py), but it does not result in the intended result.
I would appreciate it if you could explain the differences below.
#intended result
aaaa Corporation
bbb
#sample-01.py
import csv
list_a=['aaa', 'bbb']
with open('sample-01.csv', 'w', newline="") asf:
writer=csv.writer(f)
writer.writerows(list_a)
#sample-01.csv
a, a, a
b, b, b
#sample-02.py
import csv
list_a=['aaa', 'bbb']
with open('sample-02.csv', 'w', newline="") asf:
writer=csv.writer(f)
for line list_a:
writer.writerow(li)
#sample-02.csv
a, a, a
b, b, b
Below are the horizontal and vertical arrangements.
import csv
importio
list_a=['aaa', 'bbb']
with io.StringIO() as fp:
writer=csv.writer(fp)
writer.writerow(list_a)#list_a is a column for one line
for row in list_a:
writer.writerow([row])#Vertical alignment (one line specifies a list of items)
res=fp.getvalue()
print(res)
# aaa, bbb
# aaaa Corporation
# bbb
For .writerow()
, specify something like a list (iterable) and
For .writerows()
, specify a list of items (ro's literables)
In the question writer.writerows(list_a)
or writer.writerow(li)
, the desired output is one dimension short.
Also, the string is also literate, so it is handled one character at a time
for cin 'abcde':
print(c)
a
B
c
d
e
Based on the above, you will need the following data structure to write one item at a time using .writerows()
.
rows=[['First line'],
['Second line']
['Third line']
writer.writerows (rows)
© 2024 OneMinuteCode. All rights reserved.