简体   繁体   中英

Removing files from a list of folders

I have a list of folders inside my directory and within each folder I am trying to remove all the files that start with the letter 'P'.

How can I get my second for loop to iterate over all the files from within each folder? At the moment it is just iterating over the name of each folder instead of the files from within.

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...'

Untested, and using the glob module.

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

You could also find the subdirectories with os.walk -- for example, this related -- instead of looping over each item in folder_list_path and calling os.path.isdir on it.

Use glob to find and os to remove

import glob, os

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

In your program folder is a relative path. try this modified version of your program :

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)

Use os.walk to traverse the directory.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM