Question
I need to have try-except structures to deal with any errors that may occur (which will most likely be an unreadable file path) in the
I need to have try-except structures to deal with any errors that may occur (which will most likely be an unreadable file path) in the functions of my code.
Here's what I have so far:
def writeToTextFile(filename, line):
with open(filename, 'a') as outfile:
outfile.write(line)
outfile.write(' ')
print('Line appended to file successfully.')
def readFromTextFile(filepath):
try:
file_contents = ''
with open(filepath, 'r') as infile:
for line in infile:
file_contents += line.strip() + ' '
return file_contents.lstrip()
except:
print('Error: could not open/read file')
return None
def readListFromTextFile(filepath):
try:
file_contents = []
with open(filepath, 'r') as infile:
for line in infile:
file_contents.append(line.strip())
return file_contents
except:
print('Error: could not open/read file')
return None
def main():
while True:
print('[1] Append to File')
print('[2] Read File Contents')
print('[3] Read File as List')
print('[4] Exit')
choice = input('Enter your choice: ')
if choice == '1':
filepath = input('Enter file path: ')
line = input('Enter line to append: ')
writeToTextFile(filepath, line)
elif choice == '2':
filepath = input('Enter file path: ')
lines = readFromTextFile(filepath)
print('File Contents:')
if lines is not None:
print(lines)
elif choice == '3':
filepath = input('Enter file path: ')
line_list = readListFromTextFile(filepath)
if line_list is not None:
print(line_list)
elif choice == '4':
break
print('Bye.')
if __name__ == '__main__':
main()
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