![](/img/trans.png)
[英]How can I build and stream a zip/tar archive file by file to the client?
[英]How can I check if a file exists in a tar archive with Python?
我想先使用Python验证tar归档文件中给定文件的存在,然后再将其作为类似文件的对象获取。 我已经使用isreg()
尝试过,但是可能我做错了。
如何使用Python检查tar归档文件中是否存在文件?
我试过了
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()
泰也许是错的。 实际上tai.size()
始终为0。
如果您确实需要检查,则可以使用getnames
方法和in
运算符测试成员资格:
>>> import tarfile
>>> tar = tarfile.open("sample.tar", "w")
>>> "sample.tar" in tar.getnames()
True
但是,我认为在Python(以及通常与文件系统打交道)中,捕获异常是首选。 最好尝试读取并捕获异常,因为在检查文件的存在与以后读取文件之间总会发生事情。
>>> try:
... tar.getmember('contents.txt')
... except KeyError:
... pass
...
也许使用getnames()
?
tar = tarfile.open('sample.tar','r')
if 'test3.py' in tar.getnames():
print 'test3.py is in sample.tar'
您可以使用tar.getnames()
和in
运算符执行此操作:
$ touch a.txt
$ tar cvf a.tar a.txt
$ python
>>> names = tarfile.open('a.tar').getnames()
>>> 'a.txt' in names
True
>>> 'b.txt' in names
False
即使tar文件在子目录中有文件名,该文件也匹配,并使用normcase模仿当前操作系统的文件名大小写处理(例如,在Windows上,搜索“ readme.txt”应与tar文件中的“ README.TXT”匹配) )。
def filename_in_tar(filename, atarfile):
filename= os.path.normcase(filename)
return any(
filename == os.path.normcase(os.path.basename(tfn))
for tfn in atarfile.getnames())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.