Q:

How to copy all files with a particular prefix to new directories with python?

Suppose I have the following directory structure:
C:\Test
C:\Test\2009
C:\Test\2009\files\Artists
C:\Test\2009\files\Artists\SnoopDog
C:\Test\2009\files\Artists\SnoopDog\albums.txt
C:\Test\2009\files\Artists\SnoopDog\albums.jpg
C:\Test\2009\files\Artists\SnoopDog\hobbies.doc
C:\Test\2009\files\Artists\SmashMouth\albums.txt
C:\Test\2009\files\Artists\SmashMouth\hobbies.doc
C:\Test\2010\files\Artists\SnoopDog\albums.txt
C:\Test\2010\files\Artists\SnoopDog\albums.jpg
C:\Test\2010\files\Artists\SnoopDog\hobbies.doc

The following is the directory structure I want as a goal:
C:\ToDirectory\
C:\ToDirectory\2009\albums\SnoopDog_albums.txt
C:\ToDirectory\2009\albums\SnoopDog_albums.jpg
C:\ToDirectory\2009\albums\SmashMouth_albums.txt
C:\ToDirectory\2009\albums\SmashMouth_albums.jpg
C:\ToDirectory\2009\hobbies\SmashMouth_hobbies.doc
C:\ToDirectory\2009\hobbies\SnoopDog_hobbies.doc
C:\ToDirectory\2010\albums\SnoopDog_albums.txt
C:\ToDirectory\2010\albums\SnoopDog_albums.jpg

Assuming C:\Test contains all the files and C:\ToDirectory starts off as being an empty directory.
What is the most efficient way to have a function where I simply give its source directory C:\Test and a target directory ToDirectory and the script goes to the lowest level of C:\Test, goes through each file in the directory and checks whether the filename (ignoring extension) is a durectiry in the ToDirectory structure, if not, create it and copy the file into it with the parent directory appended at the beginning of its name with python?
I am using os.listdir and os.isdir in a series of nexted loops, but it appears to be very lengthy and though it does it job, appears inefficient...

A:

try pythons high level file operations library ( import shutil )
Also consider using pythons excellent directory walking function ( from os import walk )
You shouldn't need to copy the files but just rename the directories and filenames.

