python - 如何从python中的文件列表中复制文件

标签 python python-2.7 python-3.x copy

我得到以下程序的输出 ['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)

最佳答案

我不确定你所说的相同文件结构到底是什么意思,但我假设你想将文件复制到一个新目录但保留“/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]

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

关于python - 如何从python中的文件列表中复制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18139664/

相关文章:

python - 如何使用 python-keybinder 获取剪贴板内容

python - 如何阻止 Django/PSQL 在创建失败时自动递增表 ID

python - 无法格式化字符串

python - 使用 numpy 忽略多个变量(包括函数)

python - 即使 `__init__()` 引发异常也使用对象?

python - 如何实现一个简单的跨平台 Python 守护进程?

python - 使用 Imagekit、PIL 或 Pillow 改变饱和度?

python - 需要运行 Python 3.5

python - 遍历python中的dict和list

python - 在字典中组合字典并添加值