Skip to main content

How to read a CSV file in Python

How to read a CSV file in Python.

Here's a detailed step-by-step tutorial on how to read a CSV file in Python:

Step 1: Import the csv module To begin, you need to import the built-in csv module in Python. This module provides functionality for reading and writing CSV files.

import csv

Step 2: Open the CSV file Next, you need to open the CSV file using the open() function. Pass the file path as an argument and specify the mode as 'r' for reading.

with open('path/to/your/file.csv', 'r') as file:
# code to read the file

Step 3: Create a CSV reader object Now, create a CSV reader object using the reader() function from the csv module. Pass the file object as an argument to the reader() function.

    csv_reader = csv.reader(file)

Step 4: Read the CSV data To read the data from the CSV file, you can use a for loop to iterate over each row in the reader object. Each row will be returned as a list of values.

    for row in csv_reader:
# code to process each row

Step 5: Access the values in each row Within the loop, you can access the values in each row using indexing. The index represents the column number starting from 0. For example, row[0] will give you the value in the first column of the current row.

        value_1 = row[0]
value_2 = row[1]
# access other values as needed

Step 6: Process the data You can perform various operations on the data read from the CSV file. For example, you can store the values in variables, perform calculations, or populate a list or dictionary.

        # Example: Print the values in each row
print(value_1, value_2)

Step 7: Handle exceptions It is good practice to handle any exceptions that may occur while reading the CSV file. You can use a try-except block to catch and handle any potential errors.

with open('path/to/your/file.csv', 'r') as file:
try:
csv_reader = csv.reader(file)
for row in csv_reader:
# code to process each row
except csv.Error as e:
sys.exit('CSV file reading failed: {}'.format(e))

That's it! You now know how to read a CSV file in Python. Remember to replace 'path/to/your/file.csv' with the actual file path of your CSV file.

Additional Tips:

  • If your CSV file contains headers, you can skip the first row (header row) using the next() function before the for loop. For example: next(csv_reader).

Here's a complete example that combines all the steps mentioned above:

import csv

with open('path/to/your/file.csv', 'r') as file:
try:
csv_reader = csv.reader(file)
next(csv_reader) # Skip header row if present
for row in csv_reader:
value_1 = row[0]
value_2 = row[1]
# Process the data
print(value_1, value_2)
except csv.Error as e:
sys.exit('CSV file reading failed: {}'.format(e))

Feel free to modify and adapt the code according to your specific requirements.