Python递归查找文件并移动到一个目标目录 [英] Python recursive find files and move to one destination directory

查看:83
本文介绍了Python递归查找文件并移动到一个目标目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The script should recursively go through the rootpath directory and find all files with *.mp4 extension. Print the list of files with the directory structure. Then move the files to the destDir directory. The problem I run into is when trying to move the files to the new directory. Only files in the rootPath directory will be moved to the new destination. Files in subdirectories under rootPath causes errors:

/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'    

############## 这里是脚本

############## here is the script

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)

推荐答案

恭喜!您已经找到 os.path.join().您甚至可以在 print 调用中使用它.所以你只需要将它与 move() 一起使用:

Congratulations! You have already found os.path.join(). You even use it, on your print call. So you only have to use it with move():

shutil.move(os.path.join(root, filename), os.path.join(destDir, filename))

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

(But take care not to overwrite anything in destDir.)

这篇关于Python递归查找文件并移动到一个目标目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆