Search code examples
pythonfilefwrite

How to add new column to output file in Python?


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

Solution

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