Reading a CSV File using Python

To read a CSV file in Python, we can use the built-in csv module or the pandas library. The csv.reader() function allows reading CSV files efficiently, while Pandas provides an easier way to load and manipulate tabular data using pd.read_csv(). Let’s explore these methods to read CSV files in Python.


Examples to Read a CSV File

1. Reading a CSV File Using the csv Module

In this example, we will use Python’s built-in csv module to read a CSV file students.csv line by line and display its content.

main.py

</>
Copy
import csv

# Open and read the CSV file
with open('students.csv', 'r') as file:
    csv_reader = csv.reader(file)
    
    # Display contents of the CSV file
    for row in csv_reader:
        print(row)

Explanation:

  1. We import the csv module.
  2. We open the CSV file using the open() function in read mode ('r').
  3. The csv.reader() function is used to read the file.
  4. We iterate through each row using a for loop and print the contents.

Output:

['id', 'name', 'grade']
['101', 'Arjun', 'A']
['102', 'Ram', 'B']
['103', 'Priya', 'A']

2. Reading a CSV File as a Dictionary Using DictReader()

Instead of reading the CSV file as a list of lists, we can use csv.DictReader() to read it as a dictionary where the column headers act as keys.

main.py

</>
Copy
import csv

# Open and read the CSV file
with open('students.csv', 'r') as file:
    csv_reader = csv.DictReader(file)
    
    # Display each row as a dictionary
    for row in csv_reader:
        print(row)

Explanation:

  1. We import the csv module.
  2. The open() function is used to read the CSV file.
  3. The csv.DictReader() function reads the file as a dictionary.
  4. Each row is printed as a dictionary, with column names as keys.

Output:

{'id': '101', 'name': 'Arjun', 'grade': 'A'}
{'id': '102', 'name': 'Ram', 'grade': 'B'}
{'id': '103', 'name': 'Priya', 'grade': 'A'}

3. Reading a CSV File Using Pandas

Pandas provides an easy way to read CSV files using pd.read_csv(), which automatically handles parsing.

main.py

</>
Copy
import pandas as pd

# Read CSV file using pandas
df = pd.read_csv('students.csv')

# Display DataFrame
print(df)

Explanation:

  1. We import the pandas library.
  2. The pd.read_csv() function is used to load the CSV file into a DataFrame.
  3. We print the DataFrame to display its contents in tabular format.

Output:

    Name  Age         City
0  Alice   25     New York
1    Bob   30  Los Angeles
2 Charlie   28     Chicago

4. Reading a CSV File with a Custom Delimiter

Some CSV files may use a different delimiter such as ; instead of ,. We can specify the delimiter while reading the file.

main.py

</>
Copy
import csv

# Open and read the CSV file with a different delimiter
with open('students.csv', 'r') as file:
    csv_reader = csv.reader(file, delimiter=';')
    
    # Display contents of the CSV file
    for row in csv_reader:
        print(row)

Explanation:

  1. We use the csv.reader() method.
  2. The delimiter parameter is set to ';'.
  3. Each row is printed using a loop.

Output:

['id', 'name', 'grade']
['101', 'Arjun', 'A']
['102', 'Ram', 'B']
['103', 'Priya', 'A']

Conclusion

Python provides multiple ways to read a CSV file. In this tutorial, we covered:

  1. csv.reader(): Reads a CSV file line by line as a list.
  2. csv.DictReader(): Reads CSV rows as dictionaries with column headers as keys.
  3. pandas.read_csv(): Reads CSV into a Pandas DataFrame for easier data handling.
  4. Using a Custom Delimiter: Allows reading CSV files with a delimiter other than a comma.

Choosing the right method depends on the data format and how you plan to manipulate the data.