从文件夹列表中删除文件

Removing files from a list of folders

我的目录中有一个文件夹列表,在每个文件夹中我试图删除所有以字母 'P' 开头的文件。

如何让我的第二个 for 循环遍历每个文件夹中的所有文件?目前它只是遍历每个文件夹的名称而不是其中的文件。

folder_list_path = 'C:\Users\jack\Desktop\cleanUp'
for folder in os.listdir(folder_list_path):
    print folder
    for filename in folder:
        os.chdir(folder)
        if filename.startswith("P"):
            os.unlink(filename)
            print 'Removing file that starts with P...'

未经测试,使用 glob 模块。

import os, glob

folder_list_path = 'C:\Users\jack\Desktop\cleanUp'

for folder in os.listdir(folder_list_path):
    if os.path.isdir(folder):
        print folder
        os.chdir(folder)
        for filename in glob.glob('P*'):
            print('Removing file that starts with P: %s' % filename)
            # os.unlink(filename)  # Uncomment this when you're happy with what is printed

您还可以找到带有 os.walk 的子目录 -- for example, this related -- 而不是遍历 folder_list_path 中的每个项目并对其调用 os.path.isdir

使用glob查找和os删除

import glob, os

for f in glob.glob("*.bak"):
    os.remove(f)

在你的程序文件夹中是一个相对路径。试试你的程序的这个修改版本:

import os
folder_list_path = 'C:\Users\jack\Desktop\cleanUp'
for folder in os.listdir(folder_list_path):
    print folder
    subdir=os.path.join(folder_list_path,folder)
    for file in os.listdir(subdir):
        path=os.path.join(subdir,file)
        if os.path.isfile(path) and file.startswith("P"):
            print 'Removing file that starts with P...'
            os.unlink(path)

使用os.walk遍历目录。

import os

starting_directory = u'.'
for root, dirs, files in os.walk(starting_directory):
    path = root.split('/')
    for file in files:
        if file.startswith('p'):
             os.remove(os.path.join(os.path.basename(root), file))