从文件夹列表中删除文件

2024-04-25 01:06:47 发布

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

我的目录中有一个文件夹列表,在每个文件夹中,我都试图删除以字母“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...'

Tags: 文件pathin目录文件夹名称列表for
3条回答

使用glob查找,使用os删除

import glob, os

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

未测试,并使用^{}模块。你知道吗

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。你知道吗

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

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)

相关问题 更多 >