Reading & Writing CSV Files¶
CSV (Comma Separated Values) is a very common format for data science and spreadsheets. Python has a built-in csv module to handle this.
1. Reading CSV¶
Imagine a file named students.csv:
Using csv.reader¶
import csv
with open('students.csv', mode='r') as file:
csv_reader = csv.reader(file)
for row in csv_reader:
print(row) # Each row is a list: ['Vishnu', '25', 'Surat']
2. Writing CSV¶
To write data to a CSV file, we use csv.writer.
import csv
data = [
['Name', 'Score'],
['Vishnu', 95],
['Ankit', 88]
]
with open('results.csv', mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
3. The Professional Way: csv.DictReader¶
This allows you to access data by the column headers (keys) instead of index numbers.