How to delete all files in a folder using Python?

You can use the listdir function in the os module to get all the file names in a folder, and the remove function in the os module to delete a file. Here is an example code to delete all files in a folder:

import os

folder_path = 'path/to/folder'  # 文件夹路径

# 获取文件夹中的所有文件名
file_names = os.listdir(folder_path)

# 遍历文件名列表并删除文件
for file_name in file_names:
    file_path = os.path.join(folder_path, file_name)  # 文件路径
    os.remove(file_path)

Please note that the above code will only delete files within a folder, not the subfolders. If you want to delete a folder and all its contents, including subfolders, use the rmtree function in the os module.

import os
import shutil

folder_path = 'path/to/folder'  # 文件夹路径

shutil.rmtree(folder_path)

The above code will recursively delete a folder and all its contents. Please be cautious when using the rmtree function, as it permanently deletes the folder and its contents, with no possibility of recovery. Make sure to back up important files before using it.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds