我有以下列表:
theList= ["ABCD","EFGH","IJKL","MNOP"]
我想将此列表写入CSV文件,作为单行中每列中的不同元素。最终的CSV文件应如下所示;
-----------------------------
1 | ABCD | EFGH | IJKL | MNOP |
-----------------------------
我尝试了以下代码(使用csv库),但它写入多行而不是列
tempRows = zip(theList)
with open("Final.csv", 'w', newline='', encoding="utf8") as f:
writer = csv.writer(f, delimiter=',')
for tempRow in tempRows:
writer.writerow(tempRow)
答案 0 :(得分:0)
您是否尝试将参数列表直接传递给writerow?
writer.writerow(theList)
答案 1 :(得分:0)
为什么要调用zip
然后迭代它?只需用writerow
直接致电theList
即可。
with open("Final.csv", 'w', newline='', encoding="utf8") as f:
writer = csv.writer(f, delimiter=',')
writer.writerow(theList)
答案 2 :(得分:0)
如果将每个项目放入列表中的列表中,则可以写入单行:
theList= ["ABCD","EFGH","IJKL","MNOP"]
theList = [[string for string in theList]]
out_file = r"E:\data\one_line.csv"
with open(out_file, "w", newline="") as data:
writer = csv.writer(data)
for sub_list in theList:
writer.writerow(sub_list)