Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

in python how to clean all files under one folder

  1. User

    in python how to clean all files under one folder

  2. Assistant

    To delete all files in a folder using Python, you can use the os module to list all the files in the folder and then delete each file using the os.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 .txt files, you can use os.listdir(folder_path, '*.txt').