Python recursive find files and move to one destin

2020-04-12 08:29发布

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)

2条回答
萌系小妹纸
2楼-- · 2020-04-12 09:04

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))

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

查看更多
疯言疯语
3楼-- · 2020-04-12 09:14

Change the root + filename in the last line to os.path.join(root, filename) (as seen two lines earlier)?

查看更多
登录 后发表回答