0

In bash, if I have a directory foo but no directory bar, then the command

cp -r foo bar

will create the directory bar and this directory will contain the contents of foo. The Python equivalent of this is shutil.copytree("foo", "bar").

However, if I have a directory foo and also a directory bar, then the command

cp -r foo bar

will create a new directory foo underneath bar with all the contents of foo in it.

Is there a Python equivalent of this, without

a) invoking the actual command using os.system or

b) manually extracting the base name of the directory foo, appending it to bar using os.path.join, and then running copytree

That is, does Python have a concept of copying into directories?

Update: Both of the "duplicate" questions have solutions that do not copy "into" directories but rather "over" directories. The use of such solutions would require manual extraction of the base name of directory foo, appending it to bar and then using distutils.dir_util.copy_tree. I am explicitly looking for a solution that does not require this.

If bar already exists, cp -r foo bar will create a new foo inside bar with all contents of foo. On the other hand distutils.dir_util.copy_tree will put everything in foo inside bar without creating a new foo.

Community
  • 1
  • 1
merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • The documentation for `distutils.dir_util.copy_tree` suggests that I would need to use os.path.join. – merlin2011 Apr 24 '13 at 18:09
  • @dave, please see my clarifying update. – merlin2011 Apr 24 '13 at 18:16
  • your update doesn't seem invalid. at the end of the day, if foo is a directory right under the current working directory, then cp knows how to expand it because it can get a current working directory. ``os.path.join`` is not necessary if your cp is relative to ur os.getcwd(). – CppLearner Apr 24 '13 at 18:42
  • It is not the expansion of `foo` that is interesting, it is the fact that `cp` realizes that `bar` exists, and creates a new directory under it. – merlin2011 Apr 24 '13 at 18:45
  • Well mind to tell me why shutil.copy doesn't work for you? what are your constraints that makes you want to look for a new module? This is a strange requirement to be honest. Are you working on a non-conventional, cloud-based filesystem? – CppLearner Apr 24 '13 at 18:49
  • To be perfectly honest, I was simply trying to write it in less lines of code. =P – merlin2011 Apr 24 '13 at 19:02
  • no you can't. Python is a language. CPython is an implementation. The language only knows about grammar. The implementation adds modules. You as developer should take care these things explicitly. It's for safety purpose :p – CppLearner Apr 24 '13 at 19:11

0 Answers0