Cannot create a new file

Peter Hansen peter at
Tue Jun 22 11:44:56 CEST 2004

Eric Belanger wrote:

> Traceback (most recent call last):
>   File "./hnbupdate", line 42, in ?
>     localtousb()
>   File "./hnbupdate", line 12, in localtousb
> shutil.copyfile("/home/bilange/usb/.hnb","/home/bilange/.hnb-backup/"+str(int(time.time()))) 
>   File "/usr/local/lib/python2.3/", line 38, in copyfile
>     fdst = open(dst, 'wb')
> IOError: [Errno 2] No such file or directory: 
> '/home/bilange/.hnb-backup/1087869914'

There's the problem...  you can't copy to a non-existent directory.
I think in your first posting, you gave some misleading info, too.
You said that using os.system('cp ' + file1 + ' ' + file2) showed
a Python IOError, but I think it was this instead (with the full
filename instead of ...):

cp: cannot create regular file `/home/bilange/....': No such file or 

If that's true, the problem is the same there, though the error
comes from the cp program and not from Python.

What you probably want to do is use os.makedirs().  This will
create the directory, even recursively, if needed.  It normally
throws an exception if the directory already exists though, so
you probably want to put all this in a nice function:

def mycopy(src, dst):
     '''copies one file to another, quietly creating the dest dir
        if required'''

     dstdir = os.path.split(dst)[0]
     except OSError:
         pass  # dir exists, ignore error
     shutil.copyfile(src, dst)
     # optionally copy access/modification time as well
     shutil.copystat(src, dst)


More information about the Python-list mailing list