Coding-python-删除指定文件夹下文件

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import os
import shutil

def remove_files_in_folder(folder_path):
"""
删除指定文件夹下的所有文件。

:param folder_path: 文件夹路径
"""
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
try:
if os.path.isfile(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}")

def main():

folders_to_clean = [ '1', '2']

for folder in folders_to_clean:
print(f"Cleaning folder: {folder}")
remove_files_in_folder(folder)
print(f"{folder} has been cleaned.")

if __name__ == "__main__":
main()