Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

Closing a File in Python

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, "

Ad: ")
                    box.insert(INSERT, self.first)
                    box.insert(END, "

Soyad: ")
                    box.insert(INSERT, self.last)        
                    box.insert(END, "

Cinsiyet: ")
                    box.insert(INSERT, gender)
                    box.insert(END, "

Ya?: ")
                    box.insert(INSERT, age)
                    box.insert(END, "

Telefon: ")
                    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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...