在Python中保存一个二维数组或列表的CSV文件的最佳方法?

agyaoht7  于 5个月前  发布在  Python
关注(0)|答案(3)|浏览(57)

在Python中,我将一个2D数组/列表放在一起,可以这样表示:

a b 
c d

字符串
我想把它保存在CSV文件中,CSV文件看起来像这样:
a、B
c和d
这是我正在使用的代码。我做错了什么?

import csv

testarray = [["a", "b"], ["c", "d"]]

with open('test.csv', mode='w') as employee_file:
    employee_writer = csv.writer(employee_file, delimiter=',',  quotechar='"',
                                 quoting=csv.QUOTE_MINIMAL)
    employee_writer.writerow(testarray)

# Outputs 
# "['a', 'b']","['c', 'd']"


如何将代码更改为输出:
最好是:

a, b 
c, d


或者:

'a', 'b' 
'c', 'd'


在文本文件里?

gev0vcfq

gev0vcfq1#

如果testarray包含多行,请使用writerows而不是writerow

import csv

testarray = [["a", "b"], ["c", "d"]]

with open('test.csv', mode='w') as employee_file:
    employee_writer = csv.writer(employee_file, delimiter=',',  quotechar='"',
                                 quoting=csv.QUOTE_MINIMAL)
    employee_writer.writerows(testarray)

字符串

zxlwwiss

zxlwwiss2#

您可以使用嵌套的for循环来删除您首选格式的所有数据:

# Initialize the array
test = [['1', '2'], ['3', '4']]

# Format the array to a string
merged = ""
for group in test:
     merged += ", ".join(group) + "\n"

# Write string to file
with open("test.csv", "w") as file:
    file.write(merged)
    file.close()

字符串

rqenqsqc

rqenqsqc3#

您需要循环遍历testarray的各个条目或简单地使用writerows。

import csv

testarray = [["a", "b"], ["c", "d"]]

with open('test.csv', mode='w', newline='') as employee_file:
    employee_writer = csv.writer(employee_file)
    employee_writer.writerow(["header1", "header2"])
    employee_writer.writerows(testarray)

字符串

相关问题