7.2 CSV Files
CSV stands for Comma-Separated Values. It stores table-like data as plain text: each line is a record, and each column is a field. Fields are usually separated by commas.
CSV Structure
A simple CSV file:
ID,First Name,Last Name
9012,Rachel,Booker
2070,Laura,Grey
4081,Craig,JohnsonThe first line is often the header, which names each field. The following lines are data records.
csv Module
Python's csv module helps read and write CSV files, avoiding many formatting details you would otherwise handle manually.
The program below reads user information and generates email addresses. In this example, the school already has a user_info.csv file. Each row stores a user's ID, first name, and last name:
ID,First Name,Last Name
9012,Rachel,Booker
2070,Laura,Grey
4081,Craig,Johnson
9346,Mary,Jenkins
5079,Jamie,SmithThe email rule is: first letter of last name + first name + ID + @gmail.com, converted to lowercase. For example, Rachel Booker with ID 9012 becomes [email protected].
import csv
with open("user_info.csv", "r", encoding="UTF-8") as file:
reader = csv.reader(file)
next(reader)
user_info = list(reader)
with open("user_email.csv", "w", newline="", encoding="UTF-8") as file:
writer = csv.writer(file)
writer.writerow(["ID", "First Name", "Last Name", "Email"])
for user in user_info:
user_id, first_name, last_name = user
email = (last_name[0] + first_name + user_id + "@gmail.com").lower()
writer.writerow([user_id, first_name, last_name, email])reader is an iterator, and next(reader) advances it by one row. It is often used to skip the header. Without it, "ID", "First Name", and "Last Name" would be processed as ordinary user data.
The program creates a new user_email.csv:
ID,First Name,Last Name,Email
9012,Rachel,Booker,brachel9012@gmail.com
2070,Laura,Grey,glaura2070@gmail.com
4081,Craig,Johnson,jcraig4081@gmail.com
9346,Mary,Jenkins,jmary9346@gmail.com
5079,Jamie,Smith,sjamie5079@gmail.com