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'?
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.