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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With