Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This gist is a codebase to delete files & directories using python.
import shutil
import os
def delete_temp_file(locations):
for location in locations:
try:
# get list of all files and directories
file_dir = os.listdir(location)
only_files = []
only_dir = []
for i in file_dir:
# generate full path
full_path = os.path.join(location, i)
# checks if the given path is of file or not
if os.path.isfile(full_path):
only_files.append(full_path)
# checks if the given path is of directory or not
if os.path.isdir(full_path):
only_dir.append(full_path)
except Exception as e:
print(e)
# loop through the list that contains only files
for i in only_files:
try:
# os.chmod(i, 0o777)
os.remove(i) # removes the files
except Exception as e:
print(getattr(e, 'message', repr(e)))
# loop through the list that contains only directories
for i in only_dir:
try:
# os.chmod(i, 0o777)
shutil.rmtree(i, ignore_errors = False) # removes the the directory and all the sub-files and sub-directory it has
except Exception as e:
print(e)
locations = ['C:\\Users\\Sahil\\AppData\\Local\\Temp', 'C:\\Windows\\Temp','C:\\Windows\\Prefetch']
# call function
delete_temp_file(locations)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment