简体   繁体   中英

How can I include file name error handling with this piece of code?

I am required to include some form of error handling when the user inputs the file name such that if they put a file name which is not within the programs directory then it will appear with an error message. This is the code at the moment:

board = [] 
fileinput = input("Please enter your text file name:")        
filename = fileinput + ".txt"   
file = open(filename, "r+")
for lines in file:
    board.append(list(map(int,lines.split())))

I'm not sure where to include the try/except as if I include it like this:

board = [] 
fileinput = input("Please enter your text file name:")        
filename = fileinput + ".txt"
try:
    file = open(filename, "r+")
    except:
        print("Error: File not found")
    for lines in file:
        board.append(list(map(int,lines.split())))

Then I get the following error:

line 28, in for lines in file: NameError: name 'file' is not defined

I know there probably is a very simple solution but I am struggling with wrapping my head around it.

You should include all lines which may occur error under try , so:

board = [] 
fileinput = input("Please enter your text file name:")        
filename = fileinput + ".txt"
try:
    file = open(filename, "r+")
    for lines in file:
        board.append(list(map(int,lines.split())))
except:
    print("Error: File not found")

The way you presented, the program try to ignore error and go over, which ends with NameError: name 'file' is not defined

The second problem in your case would be with scope - file is local variable in try and you call it outside of scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM