import csv
# Open the input .csv file and read the contents
with open('input.csv', 'r') as input_file:
reader = csv.reader(input_file)
rows = [row for row in reader]
# Print the contents of the input file
print("Input file contents:")
for row in rows:
print(row)
# Initialize variables to track the lowest and highest values
lowest_value = float('inf')
highest_value = float('-inf')
lowest_date = ""
highest_date = ""
# Iterate through the rows and update the lowest and highest values
date = row[0]
value = float(row[1])
if value < lowest_value:
lowest_value = value
lowest_date = date
if value > highest_value:
highest_value = value
highest_date = date
# Print the lowest and highest values
print(f"Lowest value: {lowest_value} ({lowest_date})")
print(f"Highest value: {highest_value} ({highest_date})")
# Write the lowest and highest values to a new .csv file
with open('output.csv', 'w', newline='') as output_file:
writer = csv.writer(output_file)
writer.writerow(['Lowest Value', lowest_value, lowest_date])
writer.writerow(['Highest Value', highest_value, highest_date])
Copyright © 2024 SCHOLAR.TIPS - All rights reserved.
Answers & Comments
import csv
# Open the input .csv file and read the contents
with open('input.csv', 'r') as input_file:
reader = csv.reader(input_file)
rows = [row for row in reader]
# Print the contents of the input file
print("Input file contents:")
for row in rows:
print(row)
# Initialize variables to track the lowest and highest values
lowest_value = float('inf')
highest_value = float('-inf')
lowest_date = ""
highest_date = ""
# Iterate through the rows and update the lowest and highest values
for row in rows:
date = row[0]
value = float(row[1])
if value < lowest_value:
lowest_value = value
lowest_date = date
if value > highest_value:
highest_value = value
highest_date = date
# Print the lowest and highest values
print(f"Lowest value: {lowest_value} ({lowest_date})")
print(f"Highest value: {highest_value} ({highest_date})")
# Write the lowest and highest values to a new .csv file
with open('output.csv', 'w', newline='') as output_file:
writer = csv.writer(output_file)
writer.writerow(['Lowest Value', lowest_value, lowest_date])
writer.writerow(['Highest Value', highest_value, highest_date])