Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a file exists in a tar archive with Python?

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.

like image 672
svc Avatar asked Sep 13 '25 20:09

svc


1 Answers

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
...
like image 63
Tim McNamara Avatar answered Sep 15 '25 08:09

Tim McNamara