在Python中,可以使用os
模块来删除一个文件夹中的所有文件,但保留文件夹本身。以下是一个简单的例子:
import os
def delete_files_in_folder(folder_path):
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print(f'Failed to delete {file_path}. Reason: {e}')
# 使用示例
folder_to_delete = '/path/to/your/folder'
delete_files_in_folder(folder_to_delete)
确保替换/path/to/your/folder
为您想要清空的文件夹的实际路径。此脚本将删除指定文件夹内的所有文件和子文件夹,但不会删除文件夹本身。