我是新來的stackoverflow。對不起,如果這篇文章是多餘的,但我還沒有找到答案。另外,我對Python相當陌生。我想從tar文件中提取文件,如果它們不存在於tar文件所在的根目錄中。我試過了很多版本。我認爲在下面的代碼中有一些冗餘,並且它沒有做我需要的。它只是繼續提取和覆蓋現有的文件。Python tarfile - 檢查tar文件是否存在於外部(即已經被提取)
需要提取的文件將始終以「_B7.TIF」結尾。代碼目前需要一個參數 - 包含tar文件的目錄的完整路徑。
import os, shutil, sys, tarfile
directory = sys.argv[1]
tifFiles = []
for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith(".TIF"):
# also tried tifFiles.append(file)
tifFiles.append(file.name)
elif file.endswith(".tar.gz"):
tar = tarfile.open(root + "/" + file)
for item in tar:
if str(item) in tifFiles:
print "{0} has already been unzipped.".format(str(item))
elif "_B7" in str(item):
tar.extract(item, path=root)
shutil.rmtree(root + "\gap_mask")
這是另一個版本,似乎沒有做任何事情。我試圖簡化...
import os, shutil, sys, tarfile
directory = sys.argv[1]
for root, dirs, files in os.walk(directory):
if file not in tarfile.getnames() and file.endswith("_B7.TIF"):
tar.extract(file, path=root)
else:
print "File: {0} has already been unzipped.".format(file)
shutil.rmtree(root + "\gap_mask")
謝謝你的意見/建議。他們都以某種方式提供幫助。此代碼適用於我。
import os, shutil, sys, tarfile
folder = sys.argv[1]
listFiles = os.listdir(folder)
try:
for file in listFiles:
if file.endswith(".tar.gz"):
sceneTIF = file[:-7] + "_B7.TIF"
if os.path.exists(os.path.join(folder,sceneTIF)):
print sceneTIF, "has already been extracted."
else:
tar = tarfile.open(os.path.join(folder,file))
for item in tar:
if "_B7" in str(item):
tar.extract(item, path=folder)
shutil.rmtree(os.path.join(folder,"gap_mask")
except WindowsError:
pass
任何想法的風格/冗餘/使其更好的方法?托馬斯,你的代碼不能直接使用。我認爲這是tarfile.open組件。可能需要tarfile.open(os.path.join(directory,archive))。我只是想通過重新修改上述內容。沒有測試過。再次感謝。
你可以用'os.path.join(根文件)',而不是'根+「/」 +文件「,這是平臺相關的。 – 2013-04-28 19:50:04