[Tutor] How to get script to detect whether a file exists?

Steven D'Aprano steve at pearwood.info
Sun Aug 1 22:37:18 CEST 2010


On Mon, 2 Aug 2010 04:29:39 am Richard D. Moores wrote:
> <http://tutoree7.pastebin.com/0AkVmRVJ> is a work in progress. If I
> could get the script to tell whether or not the pickle files already
> existed, I could radically revise it (yeah, functions and all :) ).
> So how to find if a file exists?

The lazy way is with the os.file.exists() function:

if os.file.exists(filename):
    f = open(filename)


Of course, the lazy way usually ends up needing more work to fix the 
bugs it introduces. This is 2010, you're running under a multi-process 
operating system where a hundred other programs are sharing time with 
you, possibly even a multi-user system with other people reading and 
writing files. So the above is wrong, because there's no guarantee that 
just because the file exists when you call os.file.exists it will still 
be there a millisecond later when you call open. So the right way is to 
ignore os.file.exists and just open the file, catching errors:

try:
    f = open(filename)
except IOError:
    do_something_when_the_file_isnt_there()
else:
    do_something_with_file(f)




-- 
Steven D'Aprano


More information about the Tutor mailing list