Python tarfile - 检查 tar 文件中是否存在文件(即已被提取)

3
我是新来的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))。不过这个想法是在重写上述内容后才想到的。还没有测试。再次感谢。


1
你可以使用os.path.join(root, file)代替root + "/" + file,因为后者依赖于平台。 - Chris Medrela
1个回答

2

os.walk可以遍历目录树,包括子目录。但从您的描述来看,这不是您想要的。此外,只有在遇到您的tar文件之前遇到的文件才会被考虑存在。

直接检查遇到的文件是否存在要简单得多:

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接