【问题标题】:Below code will delete folders starting with date1.But i want to delete all except date1.So Please help.Thx下面的代码将删除以 date1 开头的文件夹。但我想删除除 date1 之外的所有文件夹。所以请帮助。Thx
【发布时间】:2023-03-14 19:11:01
【问题描述】:

files=[i for i in os.listdir(src) if (i.startswith(date1) and path.isdir(path.join(src, i)))]

对于文件中的 f: shutil.rmtree(path.join(src,f))

where,src=源路径 date1=特定模式

【问题讨论】:

    标签: python operating-system


    【解决方案1】:

    你可以这样做。我注释了代码来解释它。

    dirs = []
    
    # look into your root folder
    for item in os.listdir(src):
        # check if item is a directory and matches the pattern
        if(path.isdir(path.join(src, item)) and item.startswith(date1)):
            # remember it
            dirs.append(path.join(src, item))
    
    # go over all remembered directories
    for drctry in dirs:
        # look in all sub-directories
        for d, sd, files in os.walk(drctry):
            # go over all files in the directories
            for file in files:
                # check if file still exists to prevent errors
                if(path.isfile(path.join(d, file))):
                    # delete it
                    os.remove(path.join(d, file))
    
    # go over all remembered directories
    for drctry in dirs:
        # delete the tree
        shutil.rmtree(path.join(drctry))
    

    我有一个这样的测试结构:

    • 根文件夹
      • 2020-04-13
      • 2020-05-22
        • 一个
          • tst.txt
        • 两个
          • 一个
            • testt.rtf
          • test.txt

    通过我的测试,我删除了 2020-05-22 及其所有内容。

    【讨论】:

      【解决方案2】:

      您能详细说明一下您要做什么吗? “date1”是您要开始删除的父文件夹,还是您要“避免”删除的子文件夹?还是我完全不在这儿? :) 也许你可以展示一个示例结构?

      【讨论】:

      • 你好 Rox,'date1' 文件夹是我要删除的父文件夹,虽然 'date1' 也可以有子文件夹。但我想删除 'date1' 文件夹,以便其中的文件夹也应该被删除。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多