• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1138
  • Last Modified:

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

0
ronyosi
Asked:
ronyosi
  • 4
  • 3
1 Solution
 
HonorGodSoftware EngineerCommented:
I would use os.walk() to traverse the specified directory structure, and process each file, in sequence, moving it to the target (destination) directory.

Here's an example of how to use os.walk()

http://xahlee.info/perl-python/traverse_dir.html
0
 
codefluxCommented:
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.
0
 
HonorGodSoftware EngineerCommented:
What happens with the one liner if the filename already exists?
0
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

 
codefluxCommented:
The file name will be overwritten.  You didn't say anything about duplicate file names. ;)
0
 
HonorGodSoftware EngineerCommented:
:-)   I didn't ask the original question.
0
 
codefluxCommented:
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

0
 
ronyosiAuthor Commented:
Thank you for your help :)
0
 
HonorGodSoftware EngineerCommented:
Thank you for the grade and points.

Good luck & have a great day.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now