


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



BIO 340 Write a Python program that writes user input to a CSV file, reads the data back from the CSV file, and incorporates exception handling. You will perform the following steps: Prompt the user to enter their name, age, and email address. If the user does not enter a valid age as a positive integer, the program should catch this error and ask for the age again. Open a new file in write mode named user_info.csv and write the user's information to this file in CSV format. Make sure you handle exceptions if you do not have write permissions for the file or other IO errors occur. Now open the user_info.csv file in read mode. Make sure your code handles any exceptions if the file is not found or other IO errors occur. Read the content of the file and store it in a variable. Print the contents of this variable to the console/shell. Provide comments in your code to explain the logic used. Sure, here is a Python program that accomplishes the tasks you've outlined.
import csv
def validate_age(age): try: if int(age) > 0 : return True else: return False except ValueError: return False
while True: name = input("Enter your name: ") age = input("Enter your age: ") if validate_age(age): break else: print("Invalid age. Please enter a positive integer.") email = input("Enter your email: ")
This program first prompts the user for their name, age, and email. It validates the age to ensure it's a positive integer. If the age is invalid, it will keep asking until a valid age is entered. Next, it attempts to write this information to a CSV file named 'user_info.csv'. If it encounters an IOError (such as not having write permissions), it will print an error message. Then, it attempts to read the data back from the CSV file. Again, if it encounters an IOError (such as the file not being found), it will print an error message. Finally, it prints the contents of the file to the console.