0

Hello!
I am trying to write a piece of code to open a file using a 'while' loop. It should ask for the file name and, if it does not exist, ask for it again. This is the code:

while True:
    try:
        fhand = open(markFile)
    except:
        print 'File', markFile, 'cannot be opened. Try again.'
        continue

However, if it is not possible to open the file, it keeps printing the error message endlessly. Could anyone help? I would also like to do it for directories, is it the best way?
Cheers!

Dani

Edited by acrocephalus: n/a

2
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by acrocephalus
0
while True:
    fname = raw_input("File name: ")
    try:
        fhand = open(fname)
        break
    except IOError:
        print "File {0} cannot be opened.  Try again.".format(fname)
0

Thanks! This works, but I need to use 'fname' outside the loop as well. Is there a way to do it?
Cheers!

Dani

0

I solved this problem adding a fname='' at the beginning. Here it is the complete code.
Cheers!

markFile = ''
while True:
    fname = raw_input("> ")
    try:
        fhand = open(fname)
        break
    except IOError:
    print
        print "File"" {0} cannot be opened.  Try again.".format(fname)
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.