Strategy/ Advice for How to Best Attack this Problem?

Cameron Simpson cs at zip.com.au
Sat Apr 4 03:31:34 CEST 2015


On 03Apr2015 16:21, Dave Angel <davea at davea.name> wrote:
>On 04/03/2015 08:50 AM, Saran A wrote:
>>On Friday, April 3, 2015 at 8:05:14 AM UTC-4, Dave Angel wrote:
>>>On 04/02/2015 07:43 PM, Saran A wrote:
>>>>       os.mkdir('Success')
>
>>As you correctly stated:
>>>What do you do the second time through this function, when that
>>>directory is already existing?
>>>>      copy_and_move_file( 'Failure')
[...]
>>How would I ensure that this s directory is made only once and every file that is passeed goes only to 'success' or 'failure'?
>
>Well, you could use an if clause checking with os.exist().  If the 
>directory already exists, don't call the mkdir function.  That may not 
>be perfect, but it should suffice for an assignment at your level.

As a general remark that's slightly racy: checking, then doing. On all UNIX 
platforms, and probably Windows and others, mkdir is atomic: it works or it 
does not. So the reliable way tends to look like this:

  try:
    os.mkdir("blah")
  except FileExistsError:
    ... the directory exists, act accordingly ...
  except:
    ... something else went wrong, complain, abort, whatever
  else:
    ... directory successfully made ...

FileExistsError only came in in Python 3.3, for earlier Pythons catch OSError 
and check the exception's .errno against errno.EEXIST.

Cheers,
Cameron Simpson <cs at zip.com.au>

I am a Bear of Very Little Brain and long words Bother Me.
        - Winnie-the-Pooh



More information about the Python-list mailing list