Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NameError using "finally: f.close()" together with "with open(..) as f"

I have a code like this below in python.I'm using the 'with' keyword to open a file and parsing it's contents.But the error occurs when I'm trying to close the file.Please help.

Error message:"NameError:name 'f' is not defined"

try:
    user_xml_name = raw_input('Enter the xml name: ')
    xml_name = user_xml_name.replace(" ", "")

    with open(xml_name) as f:
        with open("temp_" + xml_name, "w") as f1:
            for line in f:
                f1.write(line)

except IOError:
    print print "File" + " " + user_xml_name + " " + "doesn't exist"

finally :
    f.close()
    f1.close()
like image 971
manty Avatar asked Jan 20 '26 11:01

manty


1 Answers

You don't need to close it manually. with statement will take care of it.

So, remove finally clause:

try:
    user_xml_name = raw_input('Enter the xml name: ')
    xml_name = user_xml_name.replace(" ", "")

    with open(xml_name) as f:
        with open("temp_" + xml_name, "w") as f1:
            for line in f:
                f1.write(line)
except IOError:
    print "File %s doesn't exist",user_xml_name
like image 197
falsetru Avatar answered Jan 22 '26 02:01

falsetru