2013-04-28 50 views
1

我是新來的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))。我只是想通過重新修改上述內容。沒有測試過。再次感謝。

+1

你可以用'os.path.join(根文件)',而不是'根+「/」 +文件「,這是平臺相關的。 – 2013-04-28 19:50:04

回答

1

os.walk遍歷目錄樹,包括子目錄。從你的描述來看,這不是你想要的。此外,只有比您的tarfiles早遇到的文件纔會被視爲存在。

這是一個容易得多,只是檢查文件是否存在,你會遇到:

import sys 
import os 
import tarfile 

directory = sys.argv[1] 

def extract_nonexisting(archive): 
    for name in archive.getnames(): 
     if os.path.exists(os.path.join(directory, name)): 
      print name, "already exists" 
     else: 
      archive.extract(name, path=directory) 

archives = [name for name in os.listdir(directory) if name.endswith("tar.gz")] 
for archive_name in archives: 
    with tarfile.open(archive_name) as archive: 
     extract_nonexisting(archive)