简体   繁体   中英

How do I write all the lines into a csv file, not just the last line?

How do I write the complete table into a new CSV file? I have looped through the necessary tuple, but I'm only getting the last line.

When I print out 'table' to the terminal, I get the whole rows and columns, but when I try to insert the rows/columns into the CSV file, it only shows the last line of the table. How do I change that?

The end goal is to merge it with another file and create a table with pandas.

This is one of the things I tried so far:

for row in zip(*([key] + (value) for key, value in sorted(dicti.items()))):
    table = [(*row,)]
    #print(table)
    with open('newfile.csv','w') as f:
        csv_f=csv.writer(f)
        csv_f.writerow(['first','middle', 'last'])
        for row in table:
            csv_f.writerow(row)
            csv_f.writerow('\n')

Thanks, your help will be appreciated. I can provide more information as needed.

In the standard library there is a function that take n lists and generates tuples with elements of each lists:

https://docs.python.org/3.9/library/functions.html#zip

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM