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

Recommended Answers

All 3 Replies

while True:
    fname = raw_input("File name: ")
    try:
        fhand = open(fname)
        break
    except IOError:
        print "File {0} cannot be opened.  Try again.".format(fname)

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

Dani

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)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.