# myTXTFile.py # Error Handling # 1. invalid inputs # 2. file write/read access issues # try except finally # custom functions def myReadFile(): # Read the data from the file # Ask the user for the filename to read fileName_Read = input("Enter filename to read: ") with open(fileName_Read, 'r') as file: data = file.read() print(data) try: # page 231 # Prompt the user for inputs fname = input("Enter Your First Name: ") lname = input("Enter Your Last Name: ") age = input("Enter Your Age: ") # Capture the input timestamp import datetime input_datetime = datetime.datetime.now() # filename, row # Log File for all Entries per Day log_day = input_datetime.strftime("%m%d%Y") string_fileName = "Entries_" + str(log_day) + ".txt" # Log filename # 2024-05-09 13:55:13.142655 now() # 05092024 string var # Entries_05092024.txt filename fileName = string_fileName ''' fileName1 = "Entries_" + str(datetime.datetime.now().strftime("%m%d%Y") + ".txt") print(fileName1) # Entries_05092024.txt ''' # file i/o i-> input o->output # methods to open an i/o 1. 'w' write 'a' append # 'w' mode -> input OVERRIDE the whole file # 'a' mode => input Appends to the end of the file # 'r' mode -> output read # Write the data to the file with open(fileName, 'a') as file: data = f"First Name: {fname} Last Name: {lname} Age: {age} Record Timestamp: {input_datetime}" file.write(data + "\n") # data string + \n operation ''' # Read the data from the file # Ask the user for the filename to read fileName_Read = input("Enter filename to read: ") with open(fileName_Read, 'r') as file: data = file.read() print(data) ''' myReadFile() # Page 238 Multiple Exceptions except FileNotFoundError as err: print("You entered a filename that does not exist. Please enter a new filename.") ''' # Read the data from the file # Ask the user for the filename to read fileName_Read = input("Enter filename to read: ") with open(fileName_Read, 'r') as file: data = file.read() print(data) ''' myReadFile() except Exception as err: print(f"An Error occurred: {err}") finally: # cleanup and dispose of any loose ends file.close() print("Thank you for using our application.")