如何删除文件夹中除一个或两个要保留的文件夹外的所有内容?

2024-04-23 09:56:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有文件夹“Folder1”,其中包含文件和文件夹,如“file1”、“file2”、“Folder11”、“Folder12”、“Folder13”等。我只想保留“Folder11”和“Folder12”,并删除其余内容。我需要帮助为同样的代码编写python脚本。你知道吗


Tags: 文件代码脚本文件夹内容file1file2folder1
1条回答
网友
1楼 · 发布于 2024-04-23 09:56:48

您可以使用^{}循环遍历目录中的每个项目和文件夹并删除它们。您还可以定义一个包含特定项目(如文件夹名称)的列表,以防止它们被删除。请记住,如果要防止文件被删除,还必须添加其格式(如文本文件的“.txt”)。你知道吗

像往常一样,删除文件时要小心。可能您想在os.remove()之前添加一个检查,或者首先用print语句(print(item))替换它,以便查看要删除的内容。你知道吗

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

相关问题 更多 >