[英]adding extra row to text file in python
I have a code that is something like that:我有一个类似的代码:
x = zip(sources,clist,RMSlist,residuelist)
name1 = string("sources")
name2 = string("clist")
name3 = string("RMSlist")
name4 = string("residuelist")
y = zip(name1,name2,name3,name4)
with open('test.csv', 'w') as f:
writer = csv.writer(f, delimiter='\t')
writer.writerows(y)
writer.writerows(x)
My goal is to write each array in a column, but i want above that column a definition (a name) for it.我的目标是将每个数组写在一列中,但我想在该列上方为其定义(名称)。 Which was my attempt with the 4 names defined.这是我对定义的 4 个名称的尝试。
It Just for the sake of understanding the text file output better它只是为了更好地理解文本文件 output
I think your problem is because you use zip()
and writerows
with char s
at the end.我认为您的问题是因为您使用zip()
和最后带有 char s
writerows
。
You should create normal list with names您应该创建带有名称的普通列表
names = ["sources", "clist", "RMSlist", "residuelist"]
and use writerow
(without char s
at the end) to write single row并使用writerow
(最后没有 char s
)写单行
writer.writerow(names) # without char `s`
BTW: Instead of name names
(which may means many objects) you can use name header
which means single object.顺便说一句:您可以使用名称header
而不是names
(可能意味着许多对象),这意味着单个 object。
header = ["sources", "clist", "RMSlist", "residuelist"]
rows = zip(sources, clist, RMSlist, residuelist)
with open('test.csv', 'w') as f:
writer = csv.writer(f, delimiter='\t')
writer.writerow(header) # without char `s` to write one row
writer.writerows(rows) # with char `s` to write many rows
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.