Exercise
CSV Data Converter
Objective
Develop Python program to read a CSV file containing comma-separated values. The file should have four data blocks per line (three text and one numeric), and the program will convert it into a text file. Each entry in the output file should have the corresponding data on separate lines. For instance, if the input file contains:
"John", "López Pérez", "Alicante", 25
"Antonio", "Pérez López", "Madrid", 27
The program should output:
John
López Pérez
Alicante
25
Antonio
Pérez López
Madrid
27
Example Python Exercise
Show Python Code
import csv
# Python program to read a CSV file and convert it into a text file
def convert_csv_to_txt(input_file, output_file):
try:
# Open the CSV file for reading
with open(input_file, 'r') as csvfile:
# Create a CSV reader object
csvreader = csv.reader(csvfile)
# Open the output text file for writing
with open(output_file, 'w') as txtfile:
for row in csvreader:
# Write each element of the row to the text file on a new line
for entry in row:
txtfile.write(entry.strip() + '\n')
print(f"Conversion successful! Data has been written to {output_file}.")
except FileNotFoundError:
print(f"Error: The file '{input_file}' does not exist.")
except Exception as e:
print(f"Error: {str(e)}")
# Example usage
convert_csv_to_txt('input.csv', 'output.txt')
Output
Example Input (CSV file: input.csv):
"John", "López Pérez", "Alicante", 25
"Antonio", "Pérez López", "Madrid", 27
Example Output (Text file: output.txt):
John
López Pérez
Alicante
25
Antonio
Pérez López
Madrid
27
Share this Python Exercise