Python 递归复制文件

Python 递归复制文件,python,python-2.7,Python,Python 2.7,我想更改包含要复制的文件的if行。在这里,我必须单独给出文件名,但我想更改它,就像它应该从包含所有文件名的列表中获取文件名一样 我该怎么做呢?从你的问题中我能理解的是,你可以简单地写: def ignore_list(path, files): filesToIgnore = [] for fileName in files: fullFileName = os.path.join(os.path.normpath(path), fileName)

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


我该怎么做呢?

从你的问题中我能理解的是,你可以简单地写:

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)
其中
fileNameList
是要复制的文件名列表

更新:

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

您还可以编写如下方法

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

文件名列表看起来怎么样?如果它是一个要忽略的文件列表,为什么不将其传递到
ignore=
?如果我得到正确的答案,你的方法ignore\u list应该在path目录中运行,并查找与If匹配的文件,然后返回一个不应复制的文件列表?我要复制的文件在“If”行中,我只想更改这一行,因此,我应该用一个列表(包含.pyc、.txt、*.ui、main.py、myfile.txt)检查“if”条件,你能用你的方法替换我代码中的“if”行吗,因为它包含*.pyc、*.ui、*.txt和main.py、myfile.txt如果你在列表中提供文件的全名(带扩展名),您不需要检查文件扩展名。只需放置允许/可接受的文件。有太多的.pyc、.ui和.txt文件,因此我无法给出所有文件的全名更新了我的代码,现在您可以创建允许扩展名列表和允许文件名列表。我尝试了您的方法(更新:),但生成的目录为空,为什么会发生这种情况?如何在答案代码中包含复制文件的条件特定文件我已经更新了代码,这甚至应该包括特定的文件,比如在您的示例“main.py”中,您只需要将这些文件传递到单独的listshutil.copytree(srcDir,dstDir,ignore=ignore\u list)-此行给了我错误类型错误:“list”对象不可调用
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)