How to Read a CSV File in Python?

How to Read a CSV File in Python

The CSV (Comma-Separated Values) file format is a simple text file used for storing tabular data. While the data in a CSV file is typically separated by commas, other delimiters like tabs (\t), colons (:), and semicolons (;) are also supported. This format is widely used for data exchange due to its simplicity and compatibility with various tools and applications.

Complete Python Course with Advance topics:-Click here

Understanding the CSV File

Consider the following example of a CSV file named example.csv:

name, rollno, department  
Peter Parker, 009001, Civil  
Tony Stark, 009002, Chemical  

The file contains a header row with column names (name, rollno, department) followed by rows of data.

Python Code to Read the CSV File

Below is the Python script to read this file and display its contents in a user-friendly format:

# Importing the csv module  
import csv  

# Open the file using the `with` statement  
with open(r'C:\Users\YourUsername\Desktop\example.csv') as csv_file:  
    csv_reader = csv.reader(csv_file, delimiter=',')  # Specifying the delimiter as a comma  
    line_count = 0  
    
    # Iterating through each row in the file  
    for row in csv_reader:  
        if line_count == 0:  
            # Print the column names from the header row  
            print(f'Column names are: {", ".join(row)}')  
            line_count += 1  
        else:  
            # Print each row's data  
            print(f'\t{row[0]} roll number is: {row[1]} and department is: {row[2]}.')  
            line_count += 1  
    
    # Print the total number of lines processed  
    print(f'Processed {line_count} lines.')

Output

When the script runs, it produces the following output:

Column names are: name, rollno, department  
Peter Parker roll number is: 009001 and department is: Civil.  
Tony Stark roll number is: 009002 and department is: Chemical.  
Processed 3 lines.

Explanation of the Code

  1. Importing the CSV Module
    Python’s csv module offers capabilities for reading and writing CSV files with ease. It supports various delimiters for flexibility.
  2. Opening the File
    To open the file in read mode, use the open() function. The with statement ensures the file is closed automatically after its operations are completed.
  3. Reading the CSV File
    • The csv.reader() function reads the file and splits data based on the specified delimiter (comma in this case).
    • The for loop iterates over each row in the file, treating it as a list of values.
  4. Processing the Header Row
    • Usually, the join() method is used to print the column names that are found in the first row.
  5. Processing Data Rows
    • For subsequent rows, the values are accessed using their indices (row[0], row[1], and row[2]).
  6. Counting Rows
    • The line_count variable keeps track of the number of rows processed, including the header.

Updates and Best Practices

  1. Flexible File Paths
    Use relative paths or a configuration to avoid hardcoding absolute paths.
  2. Handling Large Files
    For large CSV files, consider using pandas, which offers optimized functions for reading and manipulating data. Example: import pandas as pd data = pd.read_csv(r'C:\Users\YourUsername\Desktop\example.csv') print(data)
  3. Error Handling
    Add exception handling to gracefully handle errors like file not found or incorrect delimiters: try: with open('example.csv') as csv_file: csv_reader = csv.reader(csv_file) # Processing logic here except FileNotFoundError: print("The file was not found. Please check the path.")
  4. Custom Delimiters
    If your file uses a different delimiter, specify it in csv.reader(): csv_reader = csv.reader(csv_file, delimiter=';')

Download New Real Time Projects :-Click here
PHP PROJECT:- CLICK HERE


read csv python pandas
how to read csv file in python jupyter notebook
how to read csv file in python line by line
how to read a CSV file in python
python csv to dictionary
import csv python
how to read a csv File in python ppt
csv file in python class 12
python csv reader skip header
python read csv with header
chatgpt
how to read a csv File in python pdf how to read a CSV File in python
how to read a csv file in python w3schools
how to read a csv file in python using How to Read a CSV File in Python

 

Post Comment