【问题标题】:How to copy files from list of files in python如何从python中的文件列表中复制文件
【发布时间】:2013-08-09 03:31:07
【问题描述】:

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

【问题讨论】:

  • 您是否先尝试创建新结构?

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


【解决方案1】:

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

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

【讨论】:

  • 哇!抱歉,我专注于路径的语法,并没有考虑创建 day 目录。如果您选择此答案为正确答案并删除大多数 cmets 以稍微清理一下帖子。很高兴我们能解决这个问题!
猜你喜欢
  • 2013-04-23
  • 2020-09-03
  • 2012-05-13
  • 2017-04-22
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 2014-06-07
相关资源
最近更新 更多