问题
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