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 に答える