-2

How to make a script (preferably in python, but I'm open for other ways as well) to parse through multiple subfolders and copy only files with certain extension (like .mp3 & .mp4 etc) to another folder in Linux/Ubuntu?

  • 1
    For Bash: [this question](http://stackoverflow.com/questions/15617016/cp-copy-all-files-with-a-certain-extension-from-all-subdirectories) (replace `cp` by `mv`) – Benjamin W. Feb 12 '17 at 20:41
  • I'd use `find` unless there was a compelling reason to write a custom implementation. – chepner Feb 12 '17 at 20:45

1 Answers1

2

You would want to use os.walk to walk your directory tree. Then, for each file, use os.path.splitext to get the extension. Note that splitext will return the basename, and extension.

Then use shutil.copy to copy to your target directory.

A lightweight example (using / as your assumed starting point):

import os
import os.path
import shutil    

for root, dir, files in os.walk('/'):
    for ffile in files:
        if os.path.splitext(ffile)[1] in ('.mp3', '.mp4'):
            src = os.path.join(root, ffile)
            shutil.copy(src, [YOUR_TARGET_DIR])
Jordan Bonitatis
  • 1,527
  • 14
  • 12