1

有没有办法在 csv 中垂直显示压缩文本?我尝试了许多不同类型的 \n ',' 但仍然无法使数组垂直

Excel 文件

if __name__ == '__main__': #start of program
master = Tk()
newDirRH = "C:/VSMPlots"
FileName = "J123"
TypeName = "1234"
Field = [1,2,3,4,5,6,7,8,9,10]
Court = [5,4,1,2,3,4,5,1,2,3]

for field, court in zip(Field, Court):
   stringText = ','.join((str(FileName), str(TypeName), str(Field), str(Court)))

newfile = newDirRH + "/Try1.csv"
text_file = open(newfile, "w")
x = stringText
text_file.write(x)
text_file.close()
print "Done"

这是我正在寻找您的代码的方法我似乎无法添加新列,因为所有列都会重复 10 倍

在此处输入图像描述

4

1 回答 1

4

您没有写入 CSV 数据。您正在编写列表的 Python 字符串表示形式。您正在编写整个FieldCourt列出循环的每次迭代,而不是编写fieldand court,并且 Excel 在 Python 字符串表示中看到逗号:

J123,1234,[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],[5, 4, 1, 2, 3, 4, 5, 1, 2, 3]
J123,1234,[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],[5, 4, 1, 2, 3, 4, 5, 1, 2, 3]
etc.

当你想写:

J123,1234,1,5
J123,1234,2,4
etc.

使用该csv模块生成 CSV 文件:

import csv

with open(newfile, "wb") as csvfile:
    writer = csv.writer(csvfile)
    for field, court in zip(Field, Court):
        writer.writerow([FileName, TypeName, field, court])

注意with声明;它负责为您关闭打开的文件对象。该csv模块还确保所有内容都转换为字符串。

如果您只想在第一行写一些东西,请将您的物品放在柜台上;enumerate()让这很容易:

with open(newfile, "wb") as csvfile:
    writer = csv.writer(csvfile)
    # row of headers
    writer.writerow(['FileName', 'TypeName', 'field', 'court'])

    for i, (field, court) in enumerate(zip(Field, Court)):
        row = [[FileName, TypeName] if i == 0 else ['', '']
        writer.writerow(row + [field, court])
于 2013-10-11T07:30:03.580 回答