CSV File Parser Program in Python

 

 

Introduction

CSV (Comma-Separated Values) files are commonly used to store tabular data in plain text format. Parsing and displaying the contents of a CSV file is a fundamental task in data handling and processing. This program demonstrates how to create a Python script that reads a CSV file and displays its contents in a readable format.

Objective

The objective of this program is to provide a simple Python solution for reading and parsing CSV files, enabling users to understand and visualize the data effectively.

Python Code

import csv

def parse_csv(file_path):
    try:
        with open(file_path, mode='r') as file:
            reader = csv.reader(file)
            for row in reader:
                print(row)
    except FileNotFoundError:
        print(f"Error: File '{file_path}' not found.")
    except Exception as e:
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    # Example file path (update with an actual file path to test)
    file_path = 'example.csv'
    print(f"Contents of '{file_path}':")
    parse_csv(file_path)

Program Explanation

This Python program utilizes the csv module to read and parse CSV files. Here’s a breakdown of the program structure:

  • csv.reader: Reads the contents of the CSV file line by line, returning each line as a list of values.
  • Error Handling: The tryexcept block ensures the program gracefully handles missing files or other errors during file operations.

Steps to Run the Program

  1. Ensure Python is installed on your system.
  2. Create a CSV file named example.csv in the same directory as the script, or update the file_path variable with the correct file path.
  3. Copy the code into a file named parse_csv.py.
  4. Open a terminal or command prompt and navigate to the directory containing the file.
  5. Run the script using the command: python parse_csv.py.
  6. View the parsed CSV output in the terminal.
© 2024 Learn Programming. All Rights Reserved.

 

Leave a Reply

Your email address will not be published. Required fields are marked *