PYTHON

CSV Files


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.

 

1. Reading from a CSV File

To read from a CSV file, you can use the csv.reader function.

1.1 Reading the Entire File

Example:

import csv
with open('example.csv', 'r') as file:
   reader = csv.reader(file)
   for row in reader:
       print(row)

 

1.2 Reading with a Specific Delimiter

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)

 

1.3 Reading into a Dictionary

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)
 

 

2. Writing to a CSV File

To write to a CSV file, you can use the csv.writer function.

2.1 Writing Rows

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'])
 

2.2 Writing with a Specific Delimiter

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'])
 

2.3 Writing from a Dictionary

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'})
 

 

3. Handling Different CSV Formats

3.1 Customizing the CSV Format

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'])
 

 


PYTHON