recursive find files with python

我是研究僧i 提交于 2020-01-30 11:01:26

问题


I found an example how to move all files recursively, but I would like to keep the same folder structure in the destination folder.

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(os.path.join(root, filename), os.path.join(destDir, filename))

How is it possible to modify the above code to keep the same folder structure in the destination folder?


回答1:


(This answer assumes you're working in Python 2.x)

You need to make the sub-directories as you go:

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))
        targetDir = os.path.join(destDir, root[len(rootPath):])
        if not os.path.exists(targetDir):
            os.makedirs(targetDir)
        shutil.move(os.path.join(root, filename), os.path.join(targetDir, filename))

Also note that camelCase names are not standard practice in Python. Take a look at PEP8: http://legacy.python.org/dev/peps/pep-0008/




回答2:


To move all .mp4 files from root_dir directory to dest_dir directory recursively while preserving the directory structure relative to root_dir:

#!/usr/bin/env python3
from pathlib import Path
from shutil import move

src = Path(root_dir)
dest = Path(dest_dir)
for file in src.rglob('*.mp4'):
    dest_file = dest / file.relative_to(src)
    try:
        dest_file.parent.mkdir(parents=True)
    except OSError:
        pass # ignore
    move(str(file), str(dest_file))

It uses pathlib library that is available in stdlib since Python 3.4. To install it on earlier versions:

$ pip install pathlib



回答3:


Why not just do os.system('your mv command')?



来源:https://stackoverflow.com/questions/25839942/recursive-find-files-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!