Search code examples
pythonlinuxpython-3.xfile-copying

How to perform the linux equivalent of "cp -r" in python


How to recursively copy directories (cp -r) in Python?

os.copytree results in FileExistsError: [Errno 17] File exists:.

And distutils.dir_util.copy_tree raises AttributeError: module 'distutils' has no attribute 'dir_util'

How to perform the linux equivalent on cp -r in Python?


Solution

  • Using distutils, you may want to import like this if you notice the AttributeError:

    import distutils
    from distutils import dir_util
    distutils.dir_util.copy_tree("sourceDir", "dstDir")
    

    Alternatively, you can use subprocess:

    import subprocess
    subprocess.call('cp -r sourceDir dstDir', shell=True)