proutray
proutray

Reputation: 2033

How to copy a file, recreating the directory structure, using python?

src = Folder1/Folder2/file1
(edit: Folder1 has other files and folders as well)

dst = Folder3

After copying the file, I want to have
Folder3/Folder1/Folder2/file1

I think shutil.copy doesn't recreate the folders and shutil.copytree is only for folders (edit: I could have copied folder directly if there weren't other files as well).

Upvotes: 5

Views: 10095

Answers (2)

Joe T. Boka
Joe T. Boka

Reputation: 6583

If your Folder1 contains Folder2 and Folder2 contains file1, what you can do is to copy Folder1 into Folder3 using shutil. When you do this, everything in Folder1 will be copied to Folder3 as well.

import shutil
shutil.copytree("C:/Users/Desktop/Folder1", "C:/Users/Desktop/Folder3/Folder1")

The result:

Folder3/Folder1/Folder2/file1

Make sure you put Folder1 after Folder3 at the destination as above:Folder3/Folder1")

Upvotes: 1

proutray
proutray

Reputation: 2033

src = "Folder1/Folder2/file1"
dst = "Folder3"+src
dstfolder = os.path.dirname(dst)
if not os.path.exists(dstfolder):
    os.makedirs(dstfolder)
shutil.copy(src,dst)

Upvotes: 10

Related Questions