NameError using "finally: f.close ()" together with "with open (..) as f"
I have some code similar to this in python. I am using the 'with' keyword to open the file and parse its contents. But the error comes up when I try 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()
source to share
You don't need to close it manually. The operator with
will take care of this.
So, remove the sentence finally
:
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
source to share
Here's an excerpt from " Head First Python ":
"The s operator , when used with files, can dramatically reduce the amount of code you have to write, as it negates the need to finally include a package to handle closing a potentially open data file. When you use with , you no longer need to worry about closing any open files as the python interpreter will take care of this for you.
source to share