Python
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.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)