Python递归查找文件并移动到一个目标目录

时间:2011-09-15 14:07:39

标签: python recursion shutil

脚本应递归遍历根路径目录并查找扩展名为* .mp4的所有文件。使用目录结构打印文件列表。然后将文件移动到destDir目录。我遇到的问题是尝试将文件移动到新目录时。只有rootPath目录中的文件才会移动到新目标。 rootPath下子目录中的文件会导致错误:

/Volumes/VoigtKampff/Temp/TEST/level01_test.mp4
/Volumes/VoigtKampff/Temp/TEST/Destination/2levelstest02.mp4
 Traceback (most recent call last):
  File "/Volumes/HomeFolders/idmo04/Desktop/ScriptsLibrary/Python/recursive_find.py",     line 14, in <module>
    shutil.move(root+filename, destDir+'/'+filename)
     File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/shutil.py", line 281, in move
copy2(src, real_dst)
  File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/shutil.py", line 110, in copy2
    copyfile(src, dst)
  File "/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/shutil.py", line 65, in copyfile
    with open(src, 'rb') as fsrc:
  IOError: [Errno 2] No such file or directory:       '/Volumes/VoigtKampff/Temp/TEST/Destination2levelstest02.mp4'    
##############这是脚本
import fnmatch
import os
import shutil

rootPath = '/Volumes/VoigtKampff/Temp/TEST/'
destDir = '/Volumes/VoigtKampff/Temp/TEST2/'


matches = []
for root, dirnames, filenames in os.walk(rootPath):
  for filename in fnmatch.filter(filenames, '*.mp4'):
      matches.append(os.path.join(root, filename))
      print(os.path.join(root, filename))
      shutil.move(root+filename, destDir+'/'+filename)

2 个答案:

答案 0 :(得分:7)

恭喜!您已找到os.path.join()。你甚至可以在print电话上使用它。因此,您只需将其与move()

一起使用
shutil.move(os.path.join(root, filename), os.path.join(destDir, filename))

(但请注意不要覆盖destDir中的任何内容。)

答案 1 :(得分:1)

将最后一行的root + filename更改为os.path.join(root, filename)(如前面两行所示)?