Moving specific files in subdirectories into a directory - python

BJEBN picture BJEBN · Nov 16, 2011 · Viewed 11.3k times · Source

Im rather new to python but I have been attemping to learn the basics to help in my research within geology.

Anyways I have several files that once i have extracted from their zip files (painfully slow process btw) produce several hundred subdirectories with 2-3 files in each. Now what I want to do is extract all those files ending with 'dem.tif' and place them in a seperate file (move not copy).

I may have attempted to jump into the deep end here but the code i've written runs without error so it must not be finding the files (that do exist!) as it gives me the else statement. Here is the code i've created

import os

src = 'O:\DATA\ASTER GDEM\Original\North America\UTM Zone 14\USA\Extracted' # input
dst = 'O:\DATA\ASTER GDEM\Original\North America\UTM Zone 14\USA\Analyses' # desired     location

def move():
    for (dirpath, dirs, files) in os.walk(src):
        if files.endswith('dem.tif'):
            shutil.move(os.path.join(src,files),dst)
            print ('Moving ', + files, + ' to ', + dst)
        else:
            print 'No Such File Exists'

Answer

Spencer Rathbun picture Spencer Rathbun · Nov 16, 2011

First, welcome to the community, and python! You might want to change your user name, especially if you frequent here. :)

I suggest the following (stolen from Mr. Beazley):

# genfind.py
#
# A function that generates files that match a given filename pattern

import os
import shutil
import fnmatch

def gen_find(filepat,top):
    for path, dirlist, filelist in os.walk(top):
        for name in fnmatch.filter(filelist,filepat):
            yield os.path.join(path,name)

# Example use

if __name__ == '__main__':
    src = 'O:\DATA\ASTER GDEM\Original\North America\UTM Zone 14\USA\Extracted' # input
    dst = 'O:\DATA\ASTER GDEM\Original\North America\UTM Zone 14\USA\Analyses' # desired     location

    filesToMove = gen_find("*dem.tif",src)
    for name in filesToMove:
        shutil.move(name, dst)