dir中的文件夹,进入,满足条件则删除文件

For folder in dir, enter it and delete files if condition is met

我的目录看起来像这样:

dir
|_folder1
  |_file1.py
  |_file2.png
|_folder2
  |_file1.py
  |_file2.png
|_etc..

我想进入每个文件夹并删除名称中没有.py的所有文件,只是部分问题我不知道如何解决它如何知道文件是否存在一个文件夹,如果是,则进入它。

我尝试使用 listdir() 并询问该列表中每个元素的类型,但都是 string,可能是因为它只是一个名称列表。

您应该花时间让这个功能更有效率。但是,它会做你想做的事。

import os

def deleteNonPyFiles(parent_dir):
    no_delete_kw = '.py'
    for (dirpath, dirnames, filenames) in os.walk(parent_dir):
        for file in filenames:
            if no_delete_kw not in file:
                os.remove(f'{dirpath}/{file}')
   
deleteNonPyFiles('C:/User/mydirpath')

os.walk(...) 可方便地遍历所提供文件夹下的所有文件夹和子文件夹,以及 returns 每个文件夹内所有文件的列表。然后您可以重建文件的完整路径并忽略任何以 .py.

结尾的路径

你可以试试:

import os

for dir_path, _, file_names in os.walk('/path/to/your/parent/directory'):
    for delete_me in [os.path.join(dir_path, fname) for fname in file_names if not fname.endswith('.py')]:
        print(f'REMOVING: {delete_me}')
        os.remove(delete_me)

看看:

from os import walk, remove

def get_filenames(path):
    filenames = next(walk(path), (None, None, []))[2]
    return filenames

def delete_files_without_key(path, key):
    child_dirs = next(walk(path))[1]
    for dir in child_dirs:
        files = get_filenames(f"{path}/{dir}")
        for file in files:
            if key not in file:
                remove(f"{path}/{dir}/{file}")


delete_files_without_key('/path/to/parent/directory', key=".py")