CSV (Comma-Separated Values) files are a common format for storing tabular data. Python's csv
module makes it easy to read from and write to CSV files.
To read from a CSV file, you can use the csv.reader function.
Example:
import csv
with open('example.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
If your CSV file uses a delimiter other than a comma (e.g., a tab), you can specify it using the delimiter parameter.
Example:
with open('example.tsv', 'r') as file:
reader = csv.reader(file, delimiter='\t')
for row in reader:
print(row)
Using csv.DictReader, you can read rows into a dictionary, with the keys being the column headers.
Example:
with open('example.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
print(row)
To write to a CSV file, you can use the csv.writer function.
Example:
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['Alice', 30, 'New York'])
writer.writerow(['Bob', 25, 'Los Angeles'])
Example:
with open('output.tsv', 'w', newline='') as file:
writer = csv.writer(file, delimiter='\t')
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['Alice', 30, 'New York'])
writer.writerow(['Bob', 25, 'Los Angeles'])
Using csv.DictWriter, you can write rows from a dictionary.
Example:
with open('output.csv', 'w', newline='') as file:
fieldnames = ['Name', 'Age', 'City']
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'Name': 'Alice', 'Age': 30, 'City': 'New York'})
writer.writerow({'Name': 'Bob', 'Age': 25, 'City': 'Los Angeles'})
You can customize the CSV format by specifying parameters like delimiter, quotechar, and quoting.
Example:
with open('custom.csv', 'w', newline='') as file:
writer = csv.writer(file, delimiter='|', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['Alice', 30, 'New York'])
writer.writerow(['Bob', 25, 'Los Angeles'])