Bkal05 Bkal05 -3 years ago 104
Python Question

Move files in folders to a top-level directory

I am trying to complete a script for my work that cleans up their file organization system. The last part of my script needs to go inside all folders in a given directory, and move all files in every folder to the directory. For example:

import os
path = 'C:/User/Tom/Documents'
folders = os.listdir(path)
print(folders)


Lets say the folder structure is like this:

Documents
[________ Folder A
..................[_________ File 1
..................[_________ File 2
[________ Folder B
..................[_________ File 3
..................[_________ File 4
[________ Folder C
..................[_________ File 5
..................[_________ File 6
..................[_________ File 7


My goal is to somehow go into each folder under "Documents", empty out the folders by moving all of the files one level up without having to input folder names or file names to be in the Documents path that looks like this:

Documents
[________ Folder A
[_________ File 1
[_________ File 2
[________ Folder B
[_________ File 3
[_________ File 4
[________ Folder C
[_________ File 5
[_________ File 6
[_________ File 7


I am newer to python and my only thought on how to efficiently do this would be to type out a lot of code that goes into each folder directory, and shutil.move() them. However this wouldn't work for my application as the script needs to be able to complete this task for X amount of folders with Y amount of files and not having to input each folder path.

I am asking for any advice on an efficient way I can loop through my 'folders' list and simply move the files out of the folder into the path's directory.

Sorry for the long post, I just wanted to be as detailed as possible about my question, thanks!

Answer Source

I would recommend a recursive bottom-up traversal using os.walk, and moving your files accordingly.

import os
import shutil
doc_path = 'C:/User/Tom/Documents'

for root, dirs, files in os.walk(doc_path, topdown=False):
    for file in files:
        try:
            shutil.move(os.path.join(root, file), doc_path)
        except OSError:
            pass

This will move everything to the top level directory.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download