import os # Import the os module
working_directory = r"C:\Users\Vishwesh\Folder1"
retain = ["Folder11", "Folder12", "file1.txt", "file2.txt"]
os.chdir(working_directory) # Change directory to your folder
# Loop through everything in folder in current working directory
for item in os.listdir(os.getcwd()):
if item not in retain: # If it isn't in the list for retaining
os.remove(item) # Remove the item
您可以使用^{} 循环遍历目录中的每个项目和文件夹并删除它们。您还可以定义一个包含特定项目(如文件夹名称)的列表,以防止它们被删除。请记住,如果要防止文件被删除,还必须添加其格式(如文本文件的“.txt”)。你知道吗
像往常一样,删除文件时要小心。可能您想在
os.remove()
之前添加一个检查,或者首先用print语句(print(item)
)替换它,以便查看要删除的内容。你知道吗相关问题 更多 >
编程相关推荐