How to add new column to output file in Python?

风格不统一 提交于 2019-12-02 05:46:40

问题


I have this code written in Python. How can I add a new column "qty" that contains the number "1" at each row?

This is the file tripo:

{
'1.txt': [], 
'2.txt': [], 
'5.txt': [], 
'4.txt': ['3.txt','6.txt'],
'7.txt': ['8.txt']
}

This is the code:

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

回答1:


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]))


来源:https://stackoverflow.com/questions/28941924/how-to-add-new-column-to-output-file-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!