3

我得到以下程序的输出 ['file\new.txt','file\test\test.doc',...] 如何从结果中复制文件并保持相同的目录结构。

import re
import shutil

allfileaddr = []

with open("file.cproj", 'r') as fread:

    for line in fread:
        match = re.search(r'Include',line)
        if match:
            loc = line.split('"')
            allfileaddr.append(loc[1])
    print(allfileaddr)
4

1 回答 1

2

我不确定相同文件结构的确切含义,但我假设您要将文件复制到新目录但保留“/file/test”子目录结构。

import re, os, shutil
#directory you wish to copy all the files to.
dst = "c:\path\to\dir"
src = "c:\path\to\src\dir"


with open("file.cproj", 'r') as fread:

    for line in fread:
        match = re.search(r'Include',line)
        if match:
            loc = line.split('"')
            #concatenates destination and source path with subdirectory path and copies file over.
            dst_file_path = "%s\%s" % (dst,loc[1])
            (root,file_name) = os.path.splitext(dst_file_path)


            # Creates directory if one doesn't exist

            if not os.path.isdir(root):
                     os.makedirs(root)

            src_file_path = os.path.normcase("%s/%s" % (src,loc[1]))
            shutil.copyfile(src_file_path,dst_file_path)
            print dst + loc[1]

这个小脚本将设置一个您希望将所有这些文件复制到的指定目录,同时保持原始子目录结构不变。希望这就是你要找的。如果没有,请告诉我,我可以调整它。

于 2013-08-09T04:12:40.170 回答