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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With