用于移动目录/文件的Python脚本,同时使用shutil忽略某些目录/文件?

时间:2012-11-06 17:30:02

标签: python shutil

我正在寻找构建一个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路径。

目前,它会传输所有文件/目录。我想在另一个文件中读取,允许您指定要传输的文件(而不是制作“忽略”列表)。

1 个答案:

答案 0 :(得分: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”模块来匹配您的文件名。

相关问题