[Tutor] How to get script to detect whether a file exists?
Richard D. Moores
rdmoores at gmail.com
Sun Aug 1 23:55:49 CEST 2010
On Sun, Aug 1, 2010 at 13:37, Steven D'Aprano <steve at pearwood.info> wrote:
> 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)
OK, but there are actually 2 files that need to be checked. If either
one or both are missing I need to create/recreate both. How do I do
that your way? I've forgotten the little I knew about catching errors.
My lazy way has it now as
"if not (os.path.isfile(path1) and os.path.isfile(path2)):"
Thanks,
Dick
More information about the Tutor
mailing list