Here is a Python script that reads a CSV file with semicolon (;) as the delimiter and quoted fields, and then prints its contents:
import csv
import argparse
def parse_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description='Read and print a CSV file.')
parser.add_argument('--csv_filename', type=str, required=True, help='Path to the CSV file.')
return parser.parse_args()
def read_and_print_csv(filename):
"""Read the CSV file and print its contents."""
try:
with open(filename, 'r') as file:
csv_reader = csv.reader(file, delimiter=';', quotechar='"')
for row_index, row in enumerate(csv_reader):
print(f"Row {row_index+1}: {row}")
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
def main():
args = parse_args()
read_and_print_csv(args.csv_filename)
if __name__ == "__main__":
main()
Let me explain how this script works:
-
Argument Parsing: The script uses the argparse module to define a command-line argument --csv_filename, which is required. This allows you to run the script from the terminal/command prompt and specify the CSV file you want to read.
-
CSV Reading: The csv.reader function is used with two important parameters:
delimiter=';': Specifies that the fields in the CSV are separated by semicolons.
quotechar='"': Indicates that fields are quoted with double quotes. This is actually the default behavior for csv.reader, but it's specified here for clarity.
-
Error Handling: The script includes basic error handling:
- If the specified file does not exist, it catches the
FileNotFoundError and prints a user-friendly error message.
- Any other exceptions are caught and printed. This could be useful for debugging issues like permissions errors or malformed CSV files.
-
Printing: Each row of the CSV file is printed to the console. The row number (starting from 1 for user-friendliness) is included to make it easier to refer to specific rows.
How to Run This Script:
- Save the script to a file, for example,
print_csv.py.
- Open a terminal or command prompt.
- Navigate to the directory where you saved
print_csv.py.
- Run the script by typing:
python print_csv.py --csv_filename path/to/your/file.csv
Replace path/to/your/file.csv with the actual path to your CSV file.
Example Use Case:
Suppose you have a file named example.csv in the same directory as your script, with the following content:
"Name";"Age";"City"
"John Doe";"30";"New York"
"Jane Doe";"25";"Los Angeles"
Running the script with:
python print_csv.py --csv_filename example.csv
Would output:
Row 1: ['Name', 'Age', 'City']
Row 2: ['John Doe', '30', 'New York']
Row 3: ['Jane Doe', '25', 'Los Angeles']
This shows that each row is read and printed as a list of strings, with the semicolon-delimited and quoted fields properly parsed. Enjoy!