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

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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

e.x. C:home estmyfilesmyfile.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!

Answers

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.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/12060358/how-can-i-copy-files-in-python-while-keeping-their-directory-structure

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils