3

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.