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

agyaoht7  于 2024-01-03  发布在  Python
关注(0)|答案(3)|浏览(164)

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

  1. a b
  2. c d

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

  1. import csv
  2. testarray = [["a", "b"], ["c", "d"]]
  3. with open('test.csv', mode='w') as employee_file:
  4. employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"',
  5. quoting=csv.QUOTE_MINIMAL)
  6. employee_writer.writerow(testarray)
  7. # Outputs
  8. # "['a', 'b']","['c', 'd']"


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

  1. a, b
  2. c, d


或者:

  1. 'a', 'b'
  2. 'c', 'd'


在文本文件里?

gev0vcfq

gev0vcfq1#

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

  1. import csv
  2. testarray = [["a", "b"], ["c", "d"]]
  3. with open('test.csv', mode='w') as employee_file:
  4. employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"',
  5. quoting=csv.QUOTE_MINIMAL)
  6. employee_writer.writerows(testarray)

字符串

zxlwwiss

zxlwwiss2#

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

  1. # Initialize the array
  2. test = [['1', '2'], ['3', '4']]
  3. # Format the array to a string
  4. merged = ""
  5. for group in test:
  6. merged += ", ".join(group) + "\n"
  7. # Write string to file
  8. with open("test.csv", "w") as file:
  9. file.write(merged)
  10. file.close()

字符串

rqenqsqc

rqenqsqc3#

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

  1. import csv
  2. testarray = [["a", "b"], ["c", "d"]]
  3. with open('test.csv', mode='w', newline='') as employee_file:
  4. employee_writer = csv.writer(employee_file)
  5. employee_writer.writerow(["header1", "header2"])
  6. employee_writer.writerows(testarray)

字符串

相关问题