简体   繁体   中英

Python: Copy directories, not files, from multiple locations, overwriting if same name

I have a main folder netbooks_nbo which contain more dated folders. I want to get the last seven folders (by last modified date) and copy them to somewhere on the C:\\ drive. Here's my current code:

Code looks like this:

import os
import distutils.core

def get_immediate_subdirectories(dir):
    return [os.path.join(dir, name) for name in os.listdir(dir)
            if os.path.isdir(os.path.join(dir, name))]

def main():
    path = "\\\\Network_Drive\\netbooks_nbo"
    all_dirs = get_immediate_subdirectories(path)
    all_dirs.sort(key=lambda x: os.path.getmtime(x))
    all_dirs = all_dirs[len(all_dirs)-7: len(all_dirs)]

    for i in all_dirs:
        for n in get_immediate_subdirectories(i):
            distutils.dir_util.copy_tree(n, "C:\\AllFiles")
            print "copied"+ n

The problem is that dir_util.copy_tree copies all the files, rather than the actual directories. I want to preserve the directory structure. I tried using shutil.copytree(src, dst) but it just returns an Error because C:\\AllFiles will already exist after one iteration of the for loop. And shutil.copy(src,dst) doesn't work because of some bizarre permission error.

Any ideas?

如果目录树不是太大,则可以将每个目录树打包到一个存档文件中 ,然后将每个存档文件解压缩到目标位置。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM