如何在Python中向输出文件添加新列? [英] How to add new column to output file in Python?
本文介绍了如何在Python中向输出文件添加新列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这段用Python编写的代码.如何添加每行包含数字"1"的新列"qty"?
I have this code written in Python. How can I add a new column "qty" that contains the number "1" at each row?
这是文件tripo
:
{
'1.txt': [],
'2.txt': [],
'5.txt': [],
'4.txt': ['3.txt','6.txt'],
'7.txt': ['8.txt']
}
这是代码:
with open("test.csv","wa") as f:
f.write("num\n")
for k, v in tripo.items():
if v:
f.write("{}\n".format(k.split(".")[0]))
f.write("\n".join([s.split(".")[0] for s in v])+"\n
预期的输出(给定的代码创建了第二列,而我想添加列名称"):
Expected output (the given code creates a second column, while I want to add column "name"):
name num
1 4
1 3
1 6
1 7
1 8
推荐答案
我看不到将名称"列写入文件的位置.可以这样完成:
I don't see where you're writing the name column to your file. It could be done as:
with open("test.csv","wa") as f:
f.write("name\tnum\n")
for k, v in tripo.items():
if v:
f.write("1\t")
f.write("{}\n".format(k.split('.')[0]))
for s in v:
f.write("1\t{}\n".format(s.split('.')[0]))
这篇关于如何在Python中向输出文件添加新列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文