Python: flatten directories Here is a simple Python script that I wrote with lots of help from the Python mailing list. I moves all the files of subdirectories to the top level directory. It works well for my use, but if there are things that can be improved then I would like to know. I ask in the interest of being a better Python programmer and learning the language better. Thanks.

#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import shutil

currentDir = os.getcwd()
forReal = False

if ( currentDir in ['/home/dotancohen', '/home/dotancohen/.bin'] ):
        print "Error: Will not run in "+currentDir
        exit()

if ( len(sys.argv)&gt;1 and sys.argv[1] in ['m', 'M', 'c', 'C'] ):
        forReal = True
else:
        print "\nThis is a test run. To actually perform changes, add 'm' (move) or 'c' (copy) after the program name.\n"

filesList = os.walk(currentDir)

for rootDir, folders, files in filesList:
        for f in files:
                if (rootDir!=currentDir):
                        toMove = os.path.join(rootDir, f)
                        print toMove
                        newFilename = os.path.join(currentDir,f)
                        renameNumber = 1
                        while(os.path.exists(newFilename)):
                                newFilename = os.path.join(currentDir,f)+"_"+str(renameNumber)
                                renameNumber = renameNumber+1
                        if ( forReal and sys.argv[1] in ['m', 'M'] ):
                                os.rename(toMove, newFilename)
                        elif ( forReal and sys.argv[1] in ['c', 'C'] ):
                                shutil.copy(toMove, newFilename)

if ( not forReal ):
        print "\nThis was a test run. To actually perform changes, add 'm' (move) or 'c' (copy) after the program name."
I'll typically wrap the main body of my code in a python script in a function and break the code apart into more functions, allowing me to reuse that code later.

import os
import shutil
import sys

def flattenDirectory(location, action, actuallyMoveOrCopy=True):
   """ This function will move or copy all files from subdirectories in the directory location specified by location into the main directory location folder
       location - directory to flatten
       action - string containing m(ove) or M(ove) or c(opy) or C(opy)"""
   #Your code here

if __name__ == "__Main__":
    #same code to find currentDirectory here
    actuallyMoveOrCopy = len(sys.argv)&gt;1 and sys.argv[1] in ['m', 'M', 'c', 'C']
    flattenDirectory(currentDirectory, sys.argv[1], actuallyMoveOrCopy)


Now you can still run this code as you normally would, but should you need it in another script you can use it in an import without having to worry about the code automatically running at the time of import.