Q:

Keep directory name when copying in Python 3.5

Given the following script:
import shutil

src = "C:\test"
dest = "C:\copied_test"
shutil.copytree(src, dest)

This script works for copying the contents of C:\test to C:\copied_test. How do I have to change my script so that C:\test will be copied to C:\copied_test\test, i.e. the directory name shall be kept while copying?

A:

Build the dest directory name based on the src so that it become c:\copied_test.
import os  # <----
import shutil

src = r"C:\test"
dest = r"C:\copied_test"
dest = os.path.join(dest, os.path.basename(src))  # <---
shutil.copytree(src, dest)

BTW, you need to escape \ or use raw string literal. Otherwise, \t become TAB character instead of \ and t.

