Brad Conyers
Brad Conyers

Reputation: 1251

How can I copy files in Python while keeping their directory structure?

I have a list of directories which have many sub-directories.

e.x. C:\home\test\myfiles\myfile.txt

I want to copy this to my X: drive. How do I copy myfile.txt if the X: drive only contains X:\\home?

I thought shutil would create necessary directories when copying files but I was wrong and I am not sure what to use.

Worded another way...

I want to copy C:\\home\\test\\myfiles\\myfile.txt to X:\\home\\test\\myfiles\\myfile.txt but X:\\home\\test\\myfiles does not exist.

Thanks!

Upvotes: 0

Views: 4103

Answers (2)

Brad Conyers
Brad Conyers

Reputation: 1251

So here's what I ended up doing. mgilson was right I needed to use makedirs, however I didn't need copy tree.

for filepath in myfilelist:
    try:
        with open(filepath) as f: pass
    except IOError as e:
        splitlocaldir = filepath.split(os.sep)
        splitlocaldir.remove(splitlocaldir[-1:][0])
        localdir = ""
        for item in splitlocaldir:
            localdir += item + os.sep
        if not os.path.exists(localdir):
            os.makedirs(localdir)
        shutil.copyfile(sourcefile, filepath)

This separates the directory into a list so I can pull off the filename, turning the path into a directory.

Then I stitch it back together and check to see if the directory exists.

If not I create the directory using os.makedirs.

Then I can use my original full path and copy the file in now that the directory structure exists.

Upvotes: 2

mgilson
mgilson

Reputation: 309929

You need to use os.makedirs along side shutil.copytree.

Upvotes: 2

Related Questions