Python在目录中搜索和复制文件

-1 python directory search copy file

我是python的新手所以请原谅我的无知.

我希望创建一种搜索一个文本文件的方法,以获得符合搜索条件的文件列表.然后使用结果在through/recurse目录中搜索这些文件,并将它们全部复制到一个主文件夹中.

基本上我有一个文件名大量的文本文件,我已设法搜索文件并检索所有以'.mov'结尾的文件,并将结果打印/输出到文本文件.可能有几十个文件.

然后,我如何使用这些结果递归搜索目录并将文件复制到新位置.

或者,我是以完全错误的方式解决这个问题的?

非常感谢!

Tor*_*xed 8

import os, shutil

# First, create a list and populate it with the files
# you want to find (1 file per row in myfiles.txt)
files_to_find = []
with open('myfiles.txt') as fh:
    for row in fh:
        files_to_find.append(row.strip)

# Then we recursively traverse through each folder
# and match each file against our list of files to find.
for root, dirs, files in os.walk('C:\\'):
    for _file in files:
        if _file in files_to_find:
            # If we find it, notify us about it and copy it it to C:\NewPath\
            print 'Found file in: ' + str(root)
            shutil.copy(os.path.abspath(root + '/' + _file), 'C:\\NewPath\\')
Run Code Online (Sandbox Code Playgroud)

通过询问"我如何做到这一点"而不试图找出自己,你永远不会学会成为一名优秀的程序员.我通常建议人们把这个问题打破平静.

  • Google:目录中的Python列表文件
  • 摆弄示例代码,看看什么效果最好

然后继续前进

  • Google:Python复制文件
  • 摆弄预制路径,看看你是否能够运用逻辑

然后将它们结合起来.