Question
How do I make the following code work properly: import os import csv def file_to_dictionary(file_name): trench_data = {} try: with open(file_name, 'r') as file: reader
How do I make the following code work properly:
import os
import csv
def file_to_dictionary(file_name):
trench_data = {} try:
with open(file_name, 'r') as file:
reader = csv.reader(file)
for row in reader:
trench_data[row[0]] = int(row[1])
return trench_data
except FileNotFoundError:
print("File not found.")
return {}
def display_by_name(trench_data):
print("Trench Depths by Name")
print("---------------------")
for trench in sorted(trench_data):
print("{}: {} meters".format(trench, trench_data[trench]))
def display_by_depth(trench_data):
print("Trench Depths by Depth")
print("----------------------")
for trench in sorted(trench_data, key=trench_data.get, reverse=True):
depth_in_feet = trench_data[trench] * 3.2808
print("{}: {} meters ({:.2f} feet)".format(trench, trench_data[trench], depth_in_feet))
def display_by_length(trench_data):
print("Trench Depths by Length of Name")
print("------------------------------")
for trench in sorted(trench_data, key=len):
print("{}: {} meters".format(trench, trench_data[trench]))
def menu():
choice = input("Enter N to display by name, D to display by depth, L to display by length of name, or Q to quit: ")
return choice.upper()
def main():
file_path = "C:\\Users\\Gryphon8tr\\Downloads\\Trench_Depths.csv"
trench_data = file_to_dictionary(file_path)
while True:
os.system('cls')
choice = menu()
if choice == 'N':
display_by_name(trench_data)
elif choice == 'D':
display_by_depth(trench_data)
elif choice == 'L':
display_by_length(trench_data)
elif choice == 'Q':
break
else:
print("Invalid input. Try again.")
input(" Press enter to continue...")
if __name__ == "__main__":
main()
For some reason, it returns the following error and I'm not sure why:
Traceback (most recent call last): File "C:\Users\Gryphon8tr\PycharmProjects\pythonProject\lastname_hw6.py", line 59, in main() File "C:\Users\Gryphon8tr\PycharmProjects\pythonProject\lastname_hw6.py", line 41, in main trench_data = file_to_dictionary(file_path) File "C:\Users\Gryphon8tr\PycharmProjects\pythonProject\lastname_hw6.py", line 10, in file_to_dictionary trench_data[row[0]] = int(row[1]) ValueError: invalid literal for int() with base 10: ' Max Depth (m)' Process finished with exit code 1
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started