Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving specific files in subdirectories into a directory - python

Im rather new to python but I have been attemping to learn the basics.

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'
like image 495
GeoPy Avatar asked Nov 16 '11 16:11

GeoPy


2 Answers

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)
like image 83
Spencer Rathbun Avatar answered Nov 09 '22 12:11

Spencer Rathbun


I think you've mixed up the way you should be using os.walk().

for dirpath, dirs, files in os.walk(src):
    print dirpath
    print dirs
    print files
    for filename in files:
        if filename.endswith('dem.tif'):
            shutil.move(...)
        else:
            ...
like image 3
dlamotte Avatar answered Nov 09 '22 11:11

dlamotte