Issue
I'm writing a code in Python on Spyder, using Tkinter. You can see one of my methods below. Didn't want to put my full code because it's pretty long. I need to open a file to read some information. There is not a problem in my code and it actually works pretty well (does what i want it to do) but I couldn't figure out how to close my file after I'm done with it. Wherever i put my 'myFile.close()' command it gives me another type of error. I want to learn about where should i put it. I'm a little confused about where to put it because of for and if's. Would you please help me?
*** EDITED *** With the myFile1.close() commands below it gives an "ValueError: I/O operation on closed file." error.
- I didn't use myFile1 in another place.
- There isn't another myFile1.close() command.
def login(self):
id_val = self.entry_1.get()
pass_val = self.entry_2.get()
myFile1 = open("ids.txt", "r")
for line in myFile1:
if line.find(id_val) == 0:
self.pid,password,name,gender,age,phone=line.split(",")
if password == pass_val:
box = Text(width=45, height=40)
box.place(x=1120, y=80)
self.first,self.last=name.split()
box.insert(END, "\n\n\tAd: ")
box.insert(INSERT, self.first)
box.insert(END, "\n\n\tSoyad: ")
box.insert(INSERT, self.last)
box.insert(END, "\n\n\tCinsiyet: ")
box.insert(INSERT, gender)
box.insert(END, "\n\n\tYaş: ")
box.insert(INSERT, age)
box.insert(END, "\n\n\tTelefon: ")
box.insert(INSERT, phone)
self.patient_screen()
myFile1.close()
else:
messagebox.showerror("Warning", "Wrong ID or password.")
myFile1.close()
break
else:
messagebox.showerror("Warning", "Wrong ID or password.")
myFile1.close()
break
Solution
This is the correct, but poor way to open and close a file:
f = open(filename,...)
# do something with f
f.close()
It works, but there are problems. What if you want to return
in the middle of it, or break
, or there is an exception? Then you'd have to do this:
f = open(filename, ...)
# do something with f
if condition:
f.close()
return something
# do something else with f
try:
# do something which may fail
except:
f.close()
raise
if another condition:
f.close()
return something_else
# do more with f
f.close()
This gets ugly quickly. In order to avoid that, it is best to use the context manager protocol to open files using with
keyword, as those close automatically.
The same complex example:
with open(filename, ...) as f:
# do something with f
if condition:
return something
# do something else with f
# do something which may fail
if another condition:
return something_else
# do more with f
# here, the file is closed automatically
Answered By - zvone
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.