another python style question -- copying a data file

John J. Lee jjl at pobox.com
Tue Apr 22 14:58:47 EDT 2003


guy at obstruction-no-spam.com (Guy Middleton) writes:
[...]
> I want to copy a data file, but if the file doesn't already exist, I don't
> care.  I do care about any other errors, such as wrong permissions.
> 
> I have the following code, is this a typical Python way to do this?
> 
>     try:
>         os.stat(DATAFILE)
>         os.system("cp %s %s.new" % (DATAFILE, DATAFILE))
>     except OSError, arg:
>         # ENOENT is ok, we didn't do the copy
>         # anything else is a problem
>         if arg.errno != errno.ENOENT:
>             raise

I'd probably 'look before I leap' (simply because it's simple and the
first thing that comes to mind), assuming the race condition is not
important:

if os.path.exists(DATAFILE):
    shutil.copy(DATAFILE, DATAFILE+".new")  # portable, & no subshell!

You might also want to use os.path.splitext(DATAFILE)[0] + ".new"
instead of DATAFILE+".new", to strip off any old extension first.


John




More information about the Python-list mailing list