如何删除提取和执行所需任务后提取的每个文件?

时间:2014-01-08 11:25:43

标签: python

如何删除提取所需任务后提取的每个文件?

files = glob.glob('*.tar.gz')

for f in files:
    with tarfile.open(f, 'r:gz') as tar:
        tar.extractall()

我想在这里删除那些提取的文件。

可以使用os.remove(),但我想通过第一个提取过程自动提取文件名。怎么可能?

1 个答案:

答案 0 :(得分:3)

shutil.rmtree()删除目录及其所有内容。

os.remove()删除文件。

os.rmdir()删除空目录

无论何处提取这些文件,请使用上述功能删除它们。

import os
files = glob.glob('*.tar.gz')

for f in files:
    with tarfile.open(f, 'r:gz') as tar:
        tar.extractall()
        extracted_files = os.listdir(".") #retrieves the lists of all files and folders in the current directory
        for file in extracted_files:
            if file.endswith(".tar.gz"): # do not process tar.gz files
                continue
            absolute_path = os.path.abspath(file) # get the absolute path    
            if os.path.isdir(absolute_path): # test if the path points to a directory
                shutil.rmtree(absolute_path)
            else: # normal file
                os.remove(absolute_path)