4

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)?

Community
  • 1
  • 1
simont
  • 68,704
  • 18
  • 117
  • 136

2 Answers2

10

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.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • Python 3.3 will add [separate exception classes](http://docs.python.org/dev/library/exceptions.html#os-exceptions) for each error so checking `errno` won't be needed. – interjay Aug 08 '12 at 11:09
-4

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.

Abelo2
  • 11
  • 2
    This won't tell me why my `os.remove` *doesn't* run if, say, the file isn't owned by the current user, or if it's a directory instead of a file, or if the files currently in use, or a bunch of other possible errors. – simont Aug 08 '12 at 06:09
  • It does not tell permission denied problem, etc. – xis Jul 08 '15 at 23:44