Python: CSV Files

CSV files are text-only files that are simplified versions of a spreadsheet or database.

“CSV” stands for Comma-Separated Values.

export the Excel file as a CSV file.

The CSV file looks like this:
Year, Event, Winner
1995, Best-Kept Lawn, None
1999, Gobstones, Welch National
2006, World Cup, Burkina Faso

Each row of the spreadsheet is a separate line in the CSV file.

Reading in a CSV file

import csv
with open("competitions.csv") as f:
   contents_of_file = csv.reader(f)

The contents of the CSV file returned by the csv.reader function aren’t useable yet. You must loop through the data stored in contents_of_f line by line, adding each line to a list.

with open("competitions.csv") as f:
   contents_of_f= csv.reader(f)
   potter_competitions = []

   for each line in contents_of_f:
       potter_competitions += each_line

Writing to a CSV file

with open("whatever.csv", "w", newline="") as f:
   data_handler = csv.writer(f, delimiter=",")
   data_handler.writerow(["Year", "Event", "Winner"])
   data_handler.writerow(["1995", "Best-Kept Lawn","None"])
   data_handler.writerow(["1999", "Gobstones","W Nation!"])

Appending to a CSV file

with open("whatever.csv", "a", newline="") as f:
   data_handler = csv.writer(f, delimiter=",")
   data_handler.writerow(["Year", "Event", "Winner"])
   data_handler.writerow(["1995", "Best-Kept Lawn","None"])
   data_handler.writerow(["1999", "Gobstones","W Nationl"])