The Python Oracle

is_tarfile() returns True for a blank file

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC H Dvoks String Quartet No 12 Ame

--

Chapters
00:00 Question
01:48 Accepted answer (Score 1)
02:09 Answer 2 (Score 4)
02:55 Answer 3 (Score 1)
03:22 Answer 4 (Score -1)
03:44 Thank you

--

Full question
https://stackoverflow.com/questions/3058...

Question links:
[documentation]: http://docs.python.org/library/tarfile.h...
[tarfile.py]: http://svn.python.org/projects/python/tr...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ANSWER 1

Score 4


An empty tar file is a perfectly valid, and empty, tar file. Consider, at any Unix shell prompt:

$ touch foo.tar
$ ls -l foo.tar
-rw-r--r--  1 aleax  staff  0 Jun 16 18:49 foo.tar
$ tar tvf foo.tar 
$ tar xvf foo.tar

See? The empty foo.tar is a perfectly valid tar file for the Unix tar command -- it just has nothing to show or to unpack. It would be truly problematic if Python's tar handling differed so drastically from that of tar itself! What sentence in the docs led you to believe that such a problematic, headache-inducing incompatibility is part of the specs?




ACCEPTED ANSWER

Score 1


Try this at the command line:

$ touch emptyfile
$ tar -tvf emptyfile

No errors.

It looks like an empty file simply is a valid (but useless) TAR file.




ANSWER 3

Score 1


In fact, the behaviour of "is_tarfile" seems to have changed between Python 2.6 and 2.7. In Python 2.7, is_tarfile returns False for an empty file.

$ touch /tmp/foo.tar
$ python
Python 2.7.3 (default, Jul 24 2012, 11:41:40) 
[GCC 4.6.3 20120306 (Red Hat 4.6.3-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import tarfile
>>> print tarfile.is_tarfile("/tmp/foo.tar")
False
>>> 
$