Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to delete every files extracted after extracting and doing required tasks?

Tags:

python

how to delete every files extracted after extracting doing required tasks?

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

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

I want to delete those extracted files here.

os.remove() can be used, but i want to feed up the name of the files automatically through the first extracting process. how is it possible?

like image 387
2964502 Avatar asked Sep 01 '25 05:09

2964502


1 Answers

shutil.rmtree() deletes a directory and all of its contents.

os.remove() deletes a file.

os.rmdir() deletes an empty directory

Wherever those files get extracted, use the above functions to delete them.

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)
like image 129
praveen Avatar answered Sep 02 '25 19:09

praveen