simont
simont

Reputation: 72657

Verifying that os.remove has worked

To delete a file in Python, I'm using os.remove.

The docs (linked) don't give any indication of any exceptions except for OSError:

If path is a directory, OSError is raised

How do I check for exceptions such as FileNotFound, PermissionToDeleteDenied, etc? Or is such error checking not done by the os.remove function (the docs for os.remove and os.unlink don't seem to say)?

Upvotes: 4

Views: 1465

Answers (2)

Abelo2
Abelo2

Reputation: 11

Use this code:

import os
if(os.path.exists("c:/randomDirectory/random.txt"):
    # some random code

it runs the random code if random.txt exists.

Upvotes: -4

BrenBarn
BrenBarn

Reputation: 251498

OSError exceptions have an errno attribute which you can use together with the errno module to get more information about what type of OS error occurred. See the documentation for OSError.

Upvotes: 10

Related Questions