import os
import shutil
def delete_all_files_in_folder(folder_path):
# 检查文件夹是否存在
if not os.path.exists(folder_path):
print(f"文件夹 {folder_path} 不存在")
return
# 遍历文件夹中的所有文件和子文件夹
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
# 如果是文件,则删除文件
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
print(f"已删除文件: {file_path}")
# 如果是文件夹,则递归删除文件夹及其内容
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
print(f"已删除文件夹及其中的所有内容: {file_path}")
# 示例用法
folder_to_clean = "path/to/your/folder"
delete_all_files_in_folder(folder_to_clean)
os
和 shutil
模块用于文件和目录操作。delete_all_files_in_folder
函数接收一个文件夹路径作为参数。os.path.exists
检查文件夹是否存在,如果不存在则打印提示信息并返回。os.listdir
获取文件夹中的所有文件和子文件夹。os.unlink
删除。shutil.rmtree
递归删除文件夹及其内容。请根据实际情况修改 folder_to_clean
的路径。
上一篇:python execjs
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站