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

Best way to save a CSV file of a 2 dimensional array or list in Python?

你好,在 Python 我正在组合一个 2D array/list 可以这样表示:

a b 
c d

我想将其保存在 CSV 文件中,并使 CSV 文件看起来像这样:

一个,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'

在文本文件中?

再次感谢您的帮助!

您可以使用嵌套 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包含多行。使用 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)

您需要遍历测试阵列的各个条目或简单地使用 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)