创建Python代码来清除文件资源管理器中的文件夹



我是一名IT服务台助理,必须不断为vdi清理磁盘空间。我想写一个代码,可以一次清除特定的文件夹,以节省时间。我写了一个代码,但是一次只能运行一个文件夹。有没有一种方法可以让我把它变成一个函数,为每条路径都设置变量,然后一次把它们都清除掉。示例:

import os
#path to delete
path = r"C:Usersjwalstest test"
#will check if the path is a dir or not
if os.path.exists(path):

#iterating through subfolders
for root_folder, folders, files in os.walk(path):

#checking for files
for file in files:

#file path
file_path = os.path.join(root_folder, file)

#delete the files in that path
if not os.remove(file_path):
#will print if successful
print(f"{file_path} deleted successfully")
#unsuccessful message (if this prints something went wrong)
else:
print(f"Unable to delete the {file_path}")

如果是这样,您可以这样做:

import os
#paths to delete
paths = [r"C:Usersjwalstest test", r"C:Usersjwalsanother test"]
def delete_files(path):
#will check if the path is a dir or not
if os.path.exists(path):

#iterating through subfolders
for root_folder, folders, files in os.walk(path):

#checking for files
for file in files:

#file path
file_path = os.path.join(root_folder, file)

...
for path in paths:
delete_files(path)

相关内容

  • 没有找到相关文章

最新更新