63

First thing I have to mention here, I'm new to python.

Now I have a file located in:

a/long/long/path/to/file.py

I want to copy to my home directory with a new folder created:

/home/myhome/new_folder

My expected result is:

/home/myhome/new_folder/a/long/long/path/to/file.py

Is there any existing library to do that? If no, how can I achieve that?

Alex Martian
  • 3,423
  • 7
  • 36
  • 71
Js Lim
  • 3,625
  • 6
  • 42
  • 80
  • 3
    there you go, this already explains it http://stackoverflow.com/questions/1994488/copy-file-or-directory-in-python – Samuele Mattiuzzo Oct 11 '12 at 15:20
  • 1
    May be http://docs.python.org/library/shutil.html#shutil.copyfile ? – Anton Bessonov Oct 11 '12 at 15:21
  • 1
    @Anderson Green: it is not a duplicate. The accepted answers if swapped *won't work* for the questions. They are closely related (copying stuff in Python); it doesn't make them identical. Please, read the full the question and look at the answers before voting to close next time. – jfs Feb 25 '14 at 13:18
  • it's a while ago, but generally speaking a good tactic if there is a similar but not identical question, is to reference the existing question in one's own question, and state how one's own question is different. – Hugh Perkins Dec 31 '17 at 18:50

2 Answers2

80

To create all intermediate-level destination directories you could use os.makedirs() before copying:

import os
import shutil

srcfile = 'a/long/long/path/to/file.py'
dstroot = '/home/myhome/new_folder'


assert not os.path.isabs(srcfile)
dstdir =  os.path.join(dstroot, os.path.dirname(srcfile))

os.makedirs(dstdir) # create all directories, raise an error if it already exists
shutil.copy(srcfile, dstdir)
jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • for the last line, **dstdir** is a directory, it should be ``` os.makedirs(dstdir) dstfile = os.path.join(dst, src) shutil.copyfile(src, dstfile) ``` – Js Lim Oct 12 '12 at 00:18
  • @RebornJs: `copy()` supports a directory as a second argument (note: copy() vs. copyfile()) – jfs Oct 12 '12 at 01:47
  • Oh, thanks. I'm writing my first python script, doesn't know much about the existing library. – Js Lim Oct 13 '12 at 10:44
  • spelling error, in line 'assert not os.path.isabs(scrfile)' the `scrfile` to `srcfile` – Tanky Woo Feb 25 '14 at 12:49
25

take a look at shutil. shutil.copyfile(src, dst) will copy a file to another file.

Note that shutil.copyfile will not create directories that do not already exist. for that, use os.makedirs

ewok
  • 20,148
  • 51
  • 149
  • 254