Welcome, guest | Sign In | My Account | Store | Cart

This script is placed in a location then run. All files underneath the root will be propagated to the top level, while deleting any old directory's.

Problems: If you have large files in nested folders you will be copying them multiple times.

p.s. shoulda used walk() but i'm newb

Python, 71 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
## Title: movefiles.py
## Author: Shawn Kirsch (www.shawnkirsch.com)
## Description: Recoursively delete all sub directorys while preserving
##              files to the root directory.
## Version: 1.1
## Date: Sept, 28th 2010

import os, shutil

rootdir = os.getcwd()
scriptname = 'movefiles.py'
numofdirs = 0
numofiles = 0

def printcount():
    print '-' * 40
    print "Number of Directories: " + str(numofdirs)
    print "Number of Files: " + str(numofiles)
    print '-' * 40

def exploretree():
    global numofdirs, numofiles

    for x in os.listdir(os.getcwd()):
        if os.path.isdir(x):
            ##print 'Dir : ' + x
            numofdirs += 1
            os.chdir(x)
            exploretree()
            os.chdir('..')
        else:
            ##print 'File: ' + x
            if(x != scriptname):
                numofiles += 1

def movefiles():
    print '.',##just lets the user know it hasn't crashed for large batches
    for x in os.listdir(os.getcwd()):
        if os.path.isdir(x):
            os.chdir(x)
            movefiles()
            os.chdir('..')
        if os.path.isfile(x) and os.getcwd() != rootdir:
            shutil.move(x, '..')

def deletedirs():
    global numofdirs

    for x in os.listdir(os.getcwd()):
        if os.path.isdir(x):
            os.chdir(x)
            deletedirs()
            os.chdir('..')
        try:
            os.rmdir(x)
            #print 'Removed Directory: ' + x
            numofdirs -= 1
        except:
            pass
            #print "Couldn't Delete Directory: " + x


exploretree()
printcount()

while(numofdirs!=0):
    movefiles()
    deletedirs()
    

print '\nFinished: All Files moved to the root folder.'

1 comment

Benjamin Sergeant 11 years, 2 months ago  # | flag

You can also look at the shuti modulel for operating on files. BTW it's recursive not recoursive.

Created by shawn on Tue, 28 Sep 2010 (MIT)
Python recipes (4591)
shawn's recipes (1)

Required Modules

Other Information and Tasks