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

2023-12-03

该脚本应递归地遍历 rootpath 目录并查找所有具有 *.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)

恭喜!你已经找到了os.path.join()。您甚至可以在您的print称呼。所以你只需要使用它move():

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐