Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python's tarfile.open need close()?

In the official python documentation of tarfile I don't see wether a tarfile created with

tarfile.open('example.tar', 'r:*')

should be closed once you don't need it anymore.
In some other examples (e.g. here) you often see the tarfile not to be closed.

Do I run into problems if I open the same tarfile more often in some functions without always closing it?

def example(name):
    f = tarfile.open(name, 'r:*')
    # do some other stuff
    # not closing the tarfile object
    return result

example('example.tar')
example('example.tar')

Is there a difference in opening a tarfile in 'r' instead of 'w' mode (except the obvious read/write)?
Cause in the examples they always close the tarfile if it was opened with write mode 'w'?

like image 750
m13r Avatar asked Aug 04 '14 06:08

m13r


2 Answers

Yes, a TarFile object (what tarfile.open() returns) can and should be closed.

You can use the object as a context manager, in a with statement, to have it closed automatically:

with tarfile.open(name, 'r:*') as f:
    # do whatever
    return result

A TarFile object should be treated like any other file object in Python; you could rely on the file object being closed automatically when all references to it are cleaned up, but it is much better to close it explicitly. This applies doubly so when the file is open for writing.

like image 176
Martijn Pieters Avatar answered Oct 19 '22 22:10

Martijn Pieters


The reason to close it if it was opened with mode='w' is that if you do not, the actual writes to the file may remain buffered and not visible to subsequent users of the file. So if you expect to write a file and later read it in the same program, you must close it in between. The same is true of regular file objects in Python.

You should always close your file objects. It's just extra-important when they're writable.

like image 32
John Zwinck Avatar answered Oct 19 '22 22:10

John Zwinck