0

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...'
Mauro Baraldi
  • 6,346
  • 2
  • 32
  • 43
avereux
  • 572
  • 1
  • 5
  • 15
  • `for filename in folder:` won't do what you expect it to do. – jedwards Mar 27 '15 at 17:08
  • use `os.walk` and go through all the folders/files in your directory. Add all the opes you want to remove to a new list and then use `os.unlink` . Be carefull to check your list so that you dont accidentally delete anything important – letsc Mar 27 '15 at 17:12

4 Answers4

1

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

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.

Community
  • 1
  • 1
jedwards
  • 29,432
  • 3
  • 65
  • 92
0

Use glob to find and os to remove

import glob, os

for f in glob.glob("*.bak"):
    os.remove(f)
Mauro Baraldi
  • 6,346
  • 2
  • 32
  • 43
0

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))
Kracekumar
  • 19,457
  • 10
  • 47
  • 56