Link to home
Start Free TrialLog in
Avatar of ronyosi
ronyosi

asked on

Python Script to Flatten a Directory structure

Hey Everyone,

I would like to create a python script to flatten a directory structure. This means, I have a bunch of karaoke tracks seperated into folders, I would like to have a python script that automatically moves all the files into one single directory, so that afterwords I can number those files from 1 to n.

Can somebody please given me a high level expanation of how this would be done (which libraries to use, etc) I will then try code it etc.

Thanks,
Ron

ASKER CERTIFIED SOLUTION
Avatar of HonorGod
HonorGod
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Shell one-liner:

find INPUT_DIRECTORY -type f -exec mv {} OUTPUT_DIRECTORY \;

Open in new window


Replace INPUT_DIRECTORY and OUTPUT_DIRECTORY with correct values.
What happens with the one liner if the filename already exists?
The file name will be overwritten.  You didn't say anything about duplicate file names. ;)
:-)   I didn't ask the original question.
This will rename duplicate files to have ".$$" suffix - process id of the `sh` process.  Also assumes your file names have no " in them, and leaves some possibility that the process ids roll over and start creating duplicate files, but hey, it's a one-liner. ;)

find INPUT_DIR -type f -exec sh -c 'mv --backup --suffix=.$$ "'{}'" 'OUTPUT_DIR' ' \;

Open in new window

Avatar of ronyosi
ronyosi

ASKER

Thank you for your help :)
Thank you for the grade and points.

Good luck & have a great day.