2016-12-25

Python - Move all files of a given extension, to a target folder (search nested folder hierarchy)

import os, fnmatch, shutil

# InputssourceFolder = "/absolute_path_here/"targetFolder = "/absolute_path_here/"
# Create target directory if it doesn't existif not os.path.exists( targetFolder ): 
    os.makedirs( targetFolder )

# Traverse nested folder hierarchy, and move .txt files to given folderfor root, dirs, files in os.walk( sourceFolder ):
   for filename in fnmatch.filter( files, "*.txt" ):
      shutil.move( os.path.join(root, filename), os.path.join( targetFolder, filename ) )

No comments:

Post a Comment