using os.remove() in os.walk() for loop returns FileNotFoundError

Viewed 896

I'm using Python 3.6.4 in the Anaconda command prompt.

I have a function that uses os.walk() to loop through all the available files in a root directory.

My code is:

def apply_to_files(pattern, base='.') :
    regex = re.compile(pattern)
    matches = []
    completed = ''
    for root, dirs, files in os.walk(base):
        for f in files:
            if regex.match(f):
                os.remove(f)

This triggers a FileNotFoundError specifically:

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'c.html'

I call the function like:

apply_to_files('c.*', 'C')

And the directory in which I am running the function has the structure:

root
 -C
  -c.html
  -c.txt
  -c.php
 -B
 -D

When I replace os.remove(f) with print(f) it returns all of the files just fine as you would expect. What am I missing here?

1 Answers

The files variable contain only the filenames. When trying to manipulate the files you have to add the full path:

for root, dirs, files in os.walk(base):
    for f in files:
        if regex.match(f):
            os.remove(os.path.join(root, f))
Related