CSV output from one-dimensional array does not yield intended results

Asked 1 years ago, Updated 1 years ago, 446 views

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

python python3

2022-12-28 07:16

1 Answers

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)


2022-12-28 09:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.