Search code examples
pythonfor-looppython-os

For loop throwing exception on file already deleted during os walk


I'm writing a script that walks through a directory and looks for files with the typical Windows installer extensions and deletes them. When I run this with a list (vs say checking for .msi or .exe), it breaks when going through the nested loop again. It seems as if it runs though my list, deletes one type of extension then runs through the loop again and attemtps to find the same extension then throws an exception. Here is the output when I simply print, but not remove a file:

> C:\Users\User\Documents\Python Scripts>python test.py < test_run.txt
> Found directory: . Found directory: .\test_files
>          Deleting test.cub
>          Deleting test.idt
>          Deleting test.idt
>          Deleting test.msi
>          Deleting test.msm
>          Deleting test.msp
>          Deleting test.mst
>          Deleting test.pcp
>          Deleting test1.exe

When I attempt to run it with os.remove it gives the following:

Found directory: .
Found directory: .\test_files
         Deleting test.cub
Traceback (most recent call last):
  File "test.py", line 13, in <module>
    os.remove(fileName)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'test.cub'

I read up on os walk and that seems to be working properly, I can't seem to figure out where this script is going wrong. The code is below:

import os

myList = [".msi", ".msm", ".msp", ".mst", ".idt", ".idt", ".cub", ".pcp", ".exe"]


rootDir = '.'
for dirName, subdrList, fileList in os.walk(rootDir):
    print('Found directory: %s' %dirName)
    for fileName in fileList:
        for extName in myList:
            if(fileName.endswith(extName)):
                    print('\t Deleting %s' % fileName)
                    os.remove(fileName)

Solution

  • The correct relative name of the file test.cub is .\test_files\test.cub.

    The relative name you are supplying is .\test.cub.

    As it says in the os.walk documentation:

    To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name).