tkbx
tkbx

Reputation: 16275

Find files with extension in directory and subdirectories?

I want to make a Python script to quickly organize my files on my desktop into folders based on extension. Basically, how could I use a loop to take a file, do something to it, move on to the next file, and so on?

Upvotes: 1

Views: 934

Answers (2)

Scavenger
Scavenger

Reputation: 133

I would recommend os.walk from the module os and list of the filenames

Upvotes: 0

mac
mac

Reputation: 43031

Everything you need is probably contained in the os library, more specifically in the os.path bit of it and the shutil one.

To explore a directory tree you can use os.walk and to move files around you can use shutil.move.


EDIT: a small script I hacked together to get you going:

import os
import shutil as sh
from collections import defaultdict

DESKTOP = '/home/mac/Desktop'

#This dictionary will contain: <extension>: <list_of_files> mappings
register = defaultdict(list)

#Populate the register
for dir_, dirs, fnames in os.walk('/home/mac/Desktop'):
    for fname in fnames:
        register[fname.rsplit('.', 1)[1]].append(os.path.join(dir_, fname))

#Iterate over the register, creating the directory and moving the files 
#with that extension in it.
for dirname, files in register.iteritems():
    dirname = os.path.join(DESKTOP, dirname)
    if not os.path.exists(dirname):
        os.makedirs(dirname)
    for file_ in files:
        sh.move(file_, dirname)

Upvotes: 4

Related Questions