3

コピーするファイルを記録するリストを参照しながら、ファイル/ディレクトリをあるディレクトリから別のディレクトリに移動するPythonスクリプトを作成しようとしています。

これが私がこれまでに持っているものです:

import os, shutil

// Read in origin & destination from secrets.py Readlines() stores each line followed by a '/n' in a list

    f = open('secrets.py', 'r')
    paths = f.readlines()

// Strip out those /n

    srcPath = paths[0].rstrip('\n')
    destPath = paths[1].rstrip('\n')

// Close stream

    f.close()

// Empty destPath

    for root, dirs, files in os.walk(destPath, topdown=False):
        for name in files:
            os.remove(os.path.join(root, name))
        for name in dirs:
            os.rmdir(os.path.join(root, name))

// Copy & move files into destination path

    for srcDir, dirs, files in os.walk(srcPath):
        destDir = srcDir.replace(srcPath, destPath)
        if not os.path.exists(destDir):
            os.mkdir(destDir)
        for file in files:
            srcFile = os.path.join(srcDir, file)
            destFile = os.path.join(destDir, file)
            if os.path.exists(destFile):
                os.remove(destFile)
            shutil.copy(srcFile, destDir)

secrets.pyファイルには、src/destパスが含まれています。

現在、これはすべてのファイル/ディレクトリを転送します。(「無視」リストを作成するのではなく)転送するファイルを指定できる別のファイルを読み込みたいのですが。

4

1 に答える 1

1

ファイルリストを読む必要があります

 f = open('secrets.py', 'r')
 paths = f.readlines()

 f_list = open("filelist.txt", "r")
 file_list = map(lambda x: x.rstrip('\n'), f_list.readlines())

 ....
 ....

コピーする前に確認してください

    for file in files: 
       if file in file_list# <--- this is the condition you need to add to your code
          srcFile = os.path.join(srcDir, file)
       ....

ファイルリストにコピーするファイル名のパターンが含まれている場合は、Pythonの「re」モジュールを使用してファイル名を一致させてみてください。

于 2012-11-06T19:29:37.677 に答える