Zion Oyemade
Zion Oyemade

Reputation: 433

Not found error when deleting files in directory, Python

Ok, I actually wrote a code to remove all files in a directory. However I noticed whenever a file is not found, this error message comes up:

FileNotFoundError: [WinError 2] The system cannot find the file specified: '0.txt'

My workaround was to add an exception to the code but I feel it is more of a problem with my code and that I do not need to add an error exception.

try:
    files = os.listdir(filepath)
    for file in files:
        os.remove(file)
except FileNotFoundError as exception_object: 
    print(exception_object)

Is it compulsory I must use the Except rule to ignore missing files.

Upvotes: 0

Views: 1329

Answers (1)

blhsing
blhsing

Reputation: 106435

os.listdir returns just the file names, not including their path names. You have to include the path when you call os.remove.

Change your line of file removal to:

os.remove(os.path.join(filepath, file))

Upvotes: 5

Related Questions