script that reads a CSV file .py 01-02-2024, 02:42 AM
#1
import csv
def read_csv(file_path):
data = []
with open(file_path, "r") as file:
reader = csv.reader(file)
for row in reader:
data.append(row)
return data
def process_data(data):
header = data[0]
processed_data = []
for row in data[1:]:
processed_row = {header[i]: row[i] for i in range(len(header))}
processed_data.append(processed_row)
return processed_data
def generate_report(processed_data):
for record in processed_data:
print(f"Name: {record['Name']}, Age: {record['Age']}, City: {record['City']}")
if __name__ == "__main__":
csv_file_path = "data.csv"
raw_data = read_csv(csv_file_path)
processed_data = process_data(raw_data)
generate_report(processed_data)
Explanation:
The script uses the csv module to read data from a CSV file.
read_csv function reads the CSV file and returns the data.
process_data function converts the raw data into a list of dictionaries for easier handling.
generate_report function prints a simple report using the processed data.
The if __name__ == "__main__": block ensures that the script only runs when executed directly, not when imported as a module.
def read_csv(file_path):
data = []
with open(file_path, "r") as file:
reader = csv.reader(file)
for row in reader:
data.append(row)
return data
def process_data(data):
header = data[0]
processed_data = []
for row in data[1:]:
processed_row = {header[i]: row[i] for i in range(len(header))}
processed_data.append(processed_row)
return processed_data
def generate_report(processed_data):
for record in processed_data:
print(f"Name: {record['Name']}, Age: {record['Age']}, City: {record['City']}")
if __name__ == "__main__":
csv_file_path = "data.csv"
raw_data = read_csv(csv_file_path)
processed_data = process_data(raw_data)
generate_report(processed_data)
Explanation:
The script uses the csv module to read data from a CSV file.
read_csv function reads the CSV file and returns the data.
process_data function converts the raw data into a list of dictionaries for easier handling.
generate_report function prints a simple report using the processed data.
The if __name__ == "__main__": block ensures that the script only runs when executed directly, not when imported as a module.