[Tutor] Move all files to top-level directory

Dotan Cohen dotancohen at gmail.com
Tue Apr 13 09:59:38 CEST 2010

All right, I've got it! This script will move all files of
subdirectories into cwd.

# -*- coding: utf-8 -*-
import os
currentDir = os.getcwd()
filesList = os.walk(currentDir)
for rootDirs, folders, files in filesList:
    for f in files:
        toMove      = os.path.join(rootDirs, f)
        newFilename = os.path.join(currentDir,f)
        os.rename(toMove, newFilename)

Now, features to add:
1) Smart rename: don't clobber existing files
2) Remove empty directories
3) Check that it works with spaces in filenames and directories
4) Check that it works with non-ascii UTF-8 characters in filenames
and directories
5) Confirmation button to prevent accidental runs in $HOME for instance.

Thank you to everyone who helped!

Dotan Cohen


More information about the Tutor mailing list