HelloWorld4382 HelloWorld4382 - 25 days ago 9
Python Question

Trying to perfect my code step by step, prompting user in python for file

so for this first part, prompt the user for the name of the file containing the keywords, check to make sure that the file exists and if does not exist, my program should generate an exception and exit. Have I don't this part right?

done = False
while not done:
try:
keywords = input("Enter file named keywords.txt: ")
infile = open(keywords, "r")
done = True
except IOError :
print("Error: file not found.")
exit()
try:
tweets = input("Enter file named tweets.txt: ")
infile = open(tweets, "r")
done = True
except IOError :
print("Error: file not found.")
exit() #Should exit if doesnt exist? Doesnt say in assignment


Ignore the #statement lol

Answer

Ok. I think it should look like:

try:
    file_path = input("Enter file named keywords.txt: ") # don't call it keywords, cause it is not
    with open(file_path, "r") as infile: #this will open a file and close it when needed 
        #do what you need to do with your file
except IOError : # it will catch exception if file not found
    print("Error: file not found.")
    exit()
Comments