递归复制文件

时间:2014-02-19 09:43:47

标签: python python-2.7

def ignore_list(path, files):
    filesToIgnore = []
    for fileName in files:
        fullFileName = os.path.join(os.path.normpath(path), fileName)
        if not os.path.isdir(fullFileName) and not fileName.endswith('pyc') and not fileName.endswith('ui') and not fileName.endswith('txt') and not fileName == '__main__.py' and not fileName == 'myfile.bat':
            filesToIgnore.append(fileName)

    return filesToIgnore

# Start of script    
shutil.copytree(srcDir, dstDir, ignore=ignore_list)

我想更改包含要复制的文件的if行。在这里,我必须单独给出文件名,但我想改变它,就像它应该从包含所有文件名的列表中获取文件名。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

我可以从你的问题中理解,你可以写一下:

if fileName not in fileNameList:
    filesToIgnore.append(fileName)

其中fileNameList是您要复制的文件名列表。

<强>更新

fName, fileExtension = os.path.splitext(fileName)
if fileName not in fileNameList or fileExtension not in allowedExtensionList:
    filesToIgnore.append(fileName)

答案 1 :(得分:0)

您还可以编写如下方法。

def ignore_files(path, extensions, wantedfiles):
      ignores = []

      for root, dirs, filenames in os.walk(path):
          for filename in filenames:
            if any(filename.endswith(_) for _ in extensions):
                  ignores.append(os.path.join(os.path.normpath(path), filename))
            elif filename in wantedfiles:
                  ignores.append(os.path.join(os.path.normpath(path), filename))

      return ignores

# Start of script
ignore_list = ignore_files(srcDir, ['pyc', 'uid', 'txt'])
shutil.copytree(srcDir, dstDir, ignore=ignore_list)