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
try–exceptblock ensures the program gracefully handles missing files or other errors during file operations.
Steps to Run the Program
- Ensure Python is installed on your system.
- Create a CSV file named
example.csvin the same directory as the script, or update thefile_pathvariable with the correct file path. - Copy the code into a file named
parse_csv.py. - Open a terminal or command prompt and navigate to the directory containing the file.
- Run the script using the command:
python parse_csv.py. - View the parsed CSV output in the terminal.

