2

I want to copy a certain file to a specified path. This specified path has many hierarchies of directories which do not exist in advance and need to get created during copying.

I tried shutil.copy* functions but they all seem to require that the directory at destination path is pre-created.

Is there any functions that sets up these directories as required and copies the file?

Example usage:

copy_file('resources/foo.bar', expanduser('~/a/long/long/path/foo.bar'))
missingfaktor
  • 90,905
  • 62
  • 285
  • 365
  • 1
    You can do a [`mkdir -p` equivalent operation](http://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python) before the copy. – Shawn Chin Oct 25 '12 at 10:50

1 Answers1

5

You can use os.makedirs to recursively create the arborescence you need, then use shutil.copy.

target_dir = os.path.expanduser('~/a/long/long/path')
os.makedirs(target_dir)
shutil.copy('resources/foo.bar', os.path.join(target_dir, 'foo_bar'))

That way, you decompose the problem in manageable tasks (creation then copy), which lets you handle the case where the creation of the directories crashes (following the 'explicit is better than implicit').

Pierre GM
  • 19,809
  • 3
  • 56
  • 67
  • 1
    And the argument of `makedirs` is given by [`os.path.dirname`](http://docs.python.org/library/os.path.html#os.path.dirname). – Katriel Oct 25 '12 at 10:53
  • My +1. You can also use `shutil.copytree()` if the destination directory does not exist and if you want to copy whole tree. – pepr Oct 25 '12 at 10:56