![](/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.