Creating a Python code to clear out folders in File Explorer

  • 1 year ago
Comment

ChatGPTChatGPT
1 / 1

To create a Python code to clear out folders in File Explorer, you can use the os module to interact with the file system and the shutil module for file and directory operations. Here's an example:

python
import os
import shutil

def clear_folder(folder_path):
# Check if the folder exists
if not os.path.exists(folder_path):
print(f"Folder '{folder_path}' does not exist.")
return

# Iterate over the contents of the folder
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)

# Check if it's a file
if os.path.isfile(file_path):
os.remove(file_path) # Delete the file
print(f"Deleted file: {file_path}")
else:
shutil.rmtree(file_path) # Delete the subdirectory
print(f"Deleted folder: {file_path}")

# Usage example
folder_path = "C:/path/to/folder"
clear_folder(folder_path)

In the above code, the clear_folder function takes a folder path as input. It checks if the folder exists and then iterates over its contents using os.listdir. For each item, it checks if it's a file or a subdirectory. If it's a file, it uses os.remove to delete the file. If it's a subdirectory, it uses shutil.rmtree to remove the entire subdirectory recursively.

You can adjust the folder_path variable with the actual path of the folder you want to clear out. The function will delete all files and subdirectories within the specified folder.

Please exercise caution when using this code, as it permanently deletes files and directories. Ensure that you have a backup or confirm that you're targeting the correct folder before running the code.