Skip to main content
 首页 » 编程设计

Python tarfile之检查 tar 中的文件是否存在于外部(即,已经被提取)

2025年05月04日7yjmyzz

我是 stackoverflow 的新手。对不起,如果这篇文章是多余的,但我还没有找到答案。另外,我对 Python 还很陌生。如果文件不存在于 tar 文件所在的根目录中,我想从 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 

关于风格/冗余/让它变得更好的方法有什么想法吗? Thomas,您的代码不是开箱即用的。我认为这是 tarfile.open 组件。可能需要 tarfile.open(os.path.join(directory, archive))。不过,我只是在修改上述内容后才想到这一点。没有测试过。再次感谢。

请您参考如下方法:

os.walk 遍历目录树,包括子目录。从你的描述来看,这不是你想要的。此外,只有比您的 tarfile 更早遇到的文件才会被视为存在。

检查您遇到的文件是否存在要容易得多:

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)