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