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
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to