0

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.

2
  • 3
    At first there's an indent missing after for Commented Jun 28, 2018 at 16:02
  • @SpghttCd Thanks, corrected Commented Jun 28, 2018 at 16:10

1 Answer 1

5

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.