Skip to main content

Writing to CSV

To write to a CSV file

import csv

header = ['name', 'area', 'country_code2', 'country_code3']
data = ['Afghanistan', 652090, 'AF', 'AFG']


with open("C:\\Users\\Nicholas Goh\\Desktop\\test.csv", 'w', encoding='UTF8', newline='') as f:
    writer = csv.writer(f)

    # write the header
    writer.writerow(header)

    # write the data
    writer.writerow(data)

Change 'w' to 'a' for Append instead of Overwrite

Change "C:\\Users\\Nicholas Goh\\Desktop\\test.csv" to your CSV output location