163,376 views
35 votes
35 votes
Your program must do the following tasks:

Ask the user for the path to the data file.
Open and read the data file the user provided.
If any errors occur opening or reading from the data file, the exception must be caught and the user must be told that an error occurred. The raw exception text must not be visible to the end user.
The data file is in the following format:
,
Note the day of the month is not in the data file
The month is represented by the standard 3-character abbreviation.
The data must be read into a 2-dimensional list, each inner element consists of the Month and the rainfall total. Here is a list representing the first 4 days of the data (your program must store the data in this format): [['Nov', 0.0], ['Nov', 0.0], ['Nov', 0.09], ['Nov', 0.18]]
After the data is read and stored in a 2-dimensional list, use compression to separate the data into separate lists, one list for each month.
For each month’s list, use compression again to compute the average rainfall for each month
Finally display the average daily rainfall on a bar chart similar to this:

Your program must do the following tasks: Ask the user for the path to the data file-example-1
User Matt Sephton
by
2.9k points

1 Answer

16 votes
16 votes

Here is a possible solution for the program described in the prompt:

# Ask the user for the path to the data file

data_file_path = input('Enter the path to the data file: ')

try:

# Open and read the data file

with open(data_file_path, 'r') as data_file:

data = data_file.read()

# Parse the data file contents and store in a 2-dimensional list

data_list = [[row[:3], float(row[3:])] for row in data.split('\\') if row]

# Use compression to separate the data into lists for each month

months = set([row[0] for row in data_list])

month_data = {month: [row[1] for row in data_list if row[0] == month] for month in months}

# Use compression again to compute the average rainfall for each month

month_averages = {month: sum(data)/len(data) for month, data in month_data.items()}

# Display the average daily rainfall on a bar chart

for month, average in month_averages.items():

print(f'{month}: {"*" * int(average)}')

except Exception as e:

# Catch any errors and inform the user

print('An error occurred while reading the data file.')

User Joby
by
2.4k points