我得到以下程序的输出为['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)
答案 0 :(得分: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]
这个小脚本将设置一个您想要复制所有这些文件的指定目录,同时保持原始子目录结构的完整性。希望这是你想要的。如果没有,请告诉我,我可以调整它。