Question: 3. Write program that lets the user type in the name of a file. Attempt to open the supplied file for read access. If the
3. Write program that lets the user type in the name of a file. Attempt to open the supplied file for read access. If the file exists, you can print out a confirmation message. If the file doesn't exist, you should tell the user that the file cannot be found.
Hint: use a try/except block to do it (don't just use a series of "if" statements - we want this program to be as "generic" as possible).
You will not get credit for this part of the program if you write something like the following to identify valid data files:
filename = input("Enter a filename: ")
if filename == "class1":
# open class1.txt
elif filename == "class2":
# open class2.txt
else:
print ("Sorry, I can't find this filename")
Here's the sample of the program you will use to test this problem:
Enter a class file to grade (i.e. class1 for class1.txt): foobar
File cannot be found.
Enter a class file to grade (i.e. class1 for class1.txt): class1
Successfully opened class1.txt
I tried:
x=input('Enter a class file to grade (i.e. class1 for class1.txt):')
try:
open('x', 'r')
print('Successfully opened', x, '.txt')
except:
print('File cannot be found.')
but I cannot figure out how to get the input as a .txt without requiring them to type it in, and I'm not even sure if my try/except block is close to being right. This is part of a basics class and is under functions as the lesson but none of the material is helping.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
