在csv中写入zip数组垂直

时间:2013-10-11 07:26:39

标签: python csv

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

Excel csv

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"

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

enter image description here

1 个答案:

答案 0 :(得分:3)

您没有编写CSV数据。您正在编写列表的Python字符串表示。您正在编写循环的每次迭代的整个FieldCourt列表,而不是编写fieldcourt,Excel会在Python字符串表示中看到逗号:< / p>

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 module生成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])