Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new column in a csv within a loop with python

I write data from a loop to a csv-file.

Expected outcome: Every iteration should write data in a new column.

Actually, it overwrites the data of the last iteration. How could I add a new column for every iteration?

def keywordsToCsv(filename, single_phrases):

    path = 'keywords/keywords.csv'

    with open(path, 'w', encoding='utf-8') as csvfile:
        filewriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
        filewriter.writerow([filename])
        for phrase in single_phrases:
            filewriter.writerow([phrase])
like image 556
mm1975 Avatar asked Jun 16 '26 09:06

mm1975


1 Answers

There's no need to write a new column to the CSV file for each iteration. Instead, you can delay writing the columns and keep appending the output columns to a list until the loop finishes, at which point you can write all the columns as one row together.

like image 97
blhsing Avatar answered Jun 17 '26 22:06

blhsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!