I have a directory of music that has album folders as well as individual songs on each level. How can I traverse all of these files that also are encoded in different formats(mp3, wav etc)? In addition is there a way I can rename them to a format that is more consistent to my liking using regular expressions?
Thanks
os.walk
to go over files in the directory and its sub-directories, recursivelyos.rename
to rename themThe encoding of the files pays no role here, I think. You can, of course, detect their extension (use os.path.splitext
for that) and do something based on it, but as long as you just need to rename files (i.e. manipulate their names), contents hardly matter.
I use this piece of code in a program I wrote. I use it to get a recursive list of image files, the call pattern is something like re.compile(r'\.(bmp|jpg|png)$', re.IGNORECASE)
. I think you get the idea.
def getFiles(dirname, suffixPattern=None):
dirname=os.path.normpath(dirname)
retDirs, retFiles=[], []
for root, dirs, files in os.walk(dirname):
for i in dirs:
retDirs.append(os.path.join(root, i))
for i in files:
if suffixPattern is None or \
suffixPattern.search(i) is not None:
retFiles.append((root, i))
return (retDirs, retFiles)
After you have the list, it would be easy to apply a renaming rule. os.rename
is your friend, see http://docs.python.org/library/os.html.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With