[Tutor] how to know if a file exists

Luke Paireepinart rabidpoobear at gmail.com
Thu Jan 4 05:19:24 CET 2007


shawn bright wrote:
> hello there,
> i am writing an app for linux. what command would be easiest to test 
> and see if a certain file exist ?
> i was going to do something like this
> try:
>     file = open('/path/to/file', 'rb')
>     return True
> except:
>     return False
You should except IOError here, just to be clear and such.
>
> but i thought that there would be an easier way.
The os module has some function for checking if files exist, I think.
Or you could do
if targetfile not in os.listdir(directory): return False
else: return True

But your original solution is okay.
HTH,
-Luke


More information about the Tutor mailing list