Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding python close method

Tags:

python

Is it correctly understood that the following two functions do the exact same? No matter how they are invoked.

def test():
    file = open("testfile.txt", "w")
    file.write("Hello World")

def test_2():
    with open("testfile.txt", "w") as f:
        f.write("Hello World")

Since python invokes the close method when an object is no longer referenced.

If not then this quote confuses me:

Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.

from https://www.tutorialspoint.com/python/file_close.htm

like image 684
Peter Mølgaard Pallesen Avatar asked Dec 06 '22 09:12

Peter Mølgaard Pallesen


2 Answers

No, the close method would be invoked by python garbage collector (finalizer) machinery in the first case, and immediately in the second case. If you loop calling your test or test_2 functions thousands of times, the observed behavior could be different.

File descriptors are (at least on Linux) a precious and scarce resource (when it is exhausted, the open(2) syscall fails). On Linux use getrlimit(2) with RLIMIT_NOFILE to query the limit on the number of file descriptors for your process. You should prefer the close(2) syscall to be invoked quickly once a file handle is useless.

Your question is implementation specific, operating system specific, and computer specific. You may want to understand more about operating systems by reading Operating Systems: Three Easy Pieces.

On Linux, try also the cat /proc/$$/limits or cat /proc/self/limits command in a terminal. You would see a line starting with Max open files (on my Debian desktop computer, right now in december 2019, the soft limit is 1024). See proc(5).

like image 55
Basile Starynkevitch Avatar answered Dec 10 '22 10:12

Basile Starynkevitch


No. The first one will not save the information correctly. You need to use file.close() to ensure that file is closed properly and data is saved.

On the other hand, with statement handles file operations for you. It will keep the file open for as long as the program keeps executing at the same indent level and as soon as it goes to a level higher will automatically close and save the file.

More information here.

like image 38
pavel Avatar answered Dec 10 '22 09:12

pavel