I would like to verify the existence of a given file in a tar archive with Python before I get it as a file-like object. I've tried it with isreg()
, but probably I do something wrong.
How can I check if a file exists in a tar archive with Python?
I tried
import tarfile
tar = tarfile.open("sample.tar", "w")
tar.add("test1.txt")
tar.add("test2.txt")
tar.add("test3.py")
tar.close()
tar = tarfile.open("sample.tar", "r")
tai = tar.tarinfo(name="test3.py")
print(tai.isreg())
print(tai.size())
tar.close()
Probably tai is wrong. In fact tai.size()
is always 0.
If you really need to check, then you can test for membership using the getnames
method and the in
operator:
>>> import tarfile
>>> tar = tarfile.open("sample.tar", "w")
>>> "sample.tar" in tar.getnames()
True
However, I think that in Python (and dealing with file systems in general), catching exceptions are preferred. It's better to attempt to read and catch an exception because things can always happen between checking a file's existence and reading it later.
>>> try:
... tar.getmember('contents.txt')
... except KeyError:
... pass
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With