How can you delete files in a directory using Python?

To delete all files in a directory, you can utilize the os module and shutil module in Python.

Firstly, use the os module to get all files and folders in the directory, and then use functions from the shutil module to delete files.

Here is a sample code that can clear all files in a directory.

import os
import shutil

def clear_directory(directory):
    # 遍历目录下的所有文件和文件夹
    for filename in os.listdir(directory):
        filepath = os.path.join(directory, filename)
        # 判断是否是文件
        if os.path.isfile(filepath):
            # 删除文件
            os.remove(filepath)
        # 判断是否是文件夹
        elif os.path.isdir(filepath):
            # 递归清空子目录
            shutil.rmtree(filepath)

# 要清空的目录路径
directory_path = "/path/to/directory"
# 清空目录
clear_directory(directory_path)

Please replace /path/to/directory with the actual directory path. This code will delete all files and folders within the directory, so please use it with caution.

bannerAds