gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
in python how to clean all files under one folder
- User
in python how to clean all files under one folder
- Assistant
To delete all files in a folder using Python, you can use the
osmodule to list all the files in the folder and then delete each file using theos.remove()function.Here's an example code that you can use:
import os folder_path = '/path/to/folder/' # Iterate over all the files in the folder for filename in os.listdir(folder_path): # Construct the full file path file_path = os.path.join(folder_path, filename) try: # Attempt to delete the file os.remove(file_path) print(f"Deleted {file_path}") except Exception as e: print(f"Error deleting {file_path}: {e}")Note that this code will delete all files in the specified folder. If you want to delete only certain types of files, you can modify the
os.listdir()line to filter the results based on the file type. For example, to delete only.txtfiles, you can useos.listdir(folder_path, '*.txt').