用Python保存二维数组或列表的CSV文件的最佳方法?

用Python保存二维数组或列表的CSV文件的最佳方法?,python,arrays,list,csv,export-to-csv,Python,Arrays,List,Csv,Export To Csv,您好,在Python中,我正在组合一个2D数组/列表,可以这样表示: a b c d 我想将其保存在CSV文件中,并使CSV文件如下所示: a b c d a、 b c、 d 这是我使用的代码,你能告诉我我做错了什么吗 import csv testarray = [["a", "b"], ["c", "d"]] with open('test.csv', mode='w') as employee_file: employee_writer = csv.writer(emp

您好,在Python中,我正在组合一个2D数组/列表,可以这样表示:

a b 
c d
我想将其保存在CSV文件中,并使CSV文件如下所示:

a b 
c d
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

在文本文件中


再次感谢您的帮助

您可以使用嵌套的
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()

如果
testarray
包含多行。使用
writerow
而不是
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)

您需要在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)

如果其中一个值包含
\n
,则此操作将无法正常工作。