By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,050 Members | 1,020 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,050 IT Pros & Developers. It's quick & easy.

Rename files with numbers

P: n/a
I have one folder containing mp3 files, the folder is:
C:\My Shared Folder\Rubber Soul

And the files are:
01 drive my car.mp3
02 norwegian wood.mp3
03 you won't see me.mp3
04 nowhere man.mp3
..
..
..

I'm trying to rename files to:
The Beatles - Drive My Car.mp3
The Beatles - Norwegian Wood.mp3
The Beatles - You Won't See Me.mp3
The Beatles - Nowhere Man.mp3
..
..
..

So I need to change the file number to "The Beatles -" and Capitalize
the name.
I was trying to create a function and using glob and rename, but i had
no sucsses...
Could somebody help me please,
Since now, thanks...

Oct 31 '05 #1
Share this Question
Share on Google+
16 Replies


P: n/a
On Oct 31, du************@gmail.com wrote:
I have one folder containing mp3 files, the folder is:
C:\My Shared Folder\Rubber Soul

And the files are:
03 you won't see me.mp3
.

I'm trying to rename files to:
The Beatles - You Won't See Me.mp3
.
My first suggestion is that you make better changes while you're
taking the effort to rename. I.e., don't use spaces or apostrophes
(or other shell-unfriendly characters) in file names (though some
might disagree with me on this religious issue). So for your case a
more parse-able/useful translation might be:

The_Beatles_-_You_Wont_See_Me.mp3
So I need to change the file number to "The Beatles -"
You'll probably want to use "re" for this. In a loop over
your glob'd files, something like:

re.sub(r'^\d\d\s', r'The Beatles - ', ...)
and Capitalize the name.
If you avoid the apostrophe, then 'you wont see me'.title() will do
the Right Thing.
I was trying to create a function and using glob and rename, but i
had no sucsses... Could somebody help me please,


You should post the solution you've attempted to write if you want help
fixing it.

--
_ _ ___
|V|icah |- lliott http://micah.elliott.name md*@micah.elliott.name
" " """
Oct 31 '05 #2

P: n/a
Ok, so the function simplifyed without loops:

def renamer(folder, band):
archive = #file to transform
rest = archive[3:]
print band + " -",rest.capitalize()
obs: the file names came this way(with spaces or apostrophes) from the
cd i imported.

Oct 31 '05 #3

P: n/a
On Oct 31, du************@gmail.com wrote:
...
obs: the file names came this way(with spaces or apostrophes) from
the cd i imported.


So remove them first. Here's a possible solution::

#! /usr/bin/env python

import glob, os.path

uglies = glob.glob("*.mp3")
print 'uglies:', uglies
pretties = []

for ugly in uglies:
song, ext = os.path.splitext(ugly)
song = song.replace("'", "")
song = song.replace(" ", "_")
song = song.title()
song = "The_Beatles_-_" + song[3:]
song_ext = song + ext
pretties.append(song_ext)

print 'pretties:', pretties

# rename uglies to pretties...

--
_ _ ___
|V|icah |- lliott http://micah.elliott.name md*@micah.elliott.name
" " """
Oct 31 '05 #4

P: n/a
Micah, thanks a lot,
but my focus is to learn how to acess a folder and rename all files in
this folder.

Somyhing like this:
def renamer(folder, band):
folder = #place to act
archive = #file to transform
rest = archive[3:]
print band + " -", rest.capitalize()

And than just do this:

renamer('C:\My Shared Folder\Rubber Soul', 'The Beatles')

And than pyhton alter all files in my folder. Is it possible?

I'm a beginer, for now, i just want to let the spaces and apostrophes
as they are...

Oct 31 '05 #5

P: n/a
On Oct 31, du************@gmail.com wrote:
but my focus is to learn how to acess a folder and rename all files in
this folder.


This is a little more flexible than my last post, and it does the
whole job::

#! /usr/bin/env python

import glob, os, string

def fix_ugly_song_names(songdir, band, spacerepl='_'):
"""Rename an ugly MP3 file name to a beautified shell-correct
name. Only works for files named like "03 song name.mp3".
Use `spacerepl` to alter space replacement character.
WARNING: no error-handling!
"""
# Begin working in specified `songdir`.
os.chdir(songdir)
# Shell-unfriendly characters made into a string.
badchars = ''.join( set(string.punctuation) - set('-_+.~') )
# Identity table for later translation (removal of `badchars`).
tbl = string.maketrans('', '')
# MP3 files in `songdir` having ugly characters.
uglies = glob.glob("*.mp3")
# Make some step-by-step changes to build `pretties` list.
pretties = []
for ugly in uglies:
song, ext = os.path.splitext(ugly)
song = song.translate(tbl, badchars)
song = song.replace(" ", spacerepl)
song = song.title()
song = band+spacerepl+"-"+spacerepl+song[3:]
songext = song + ext
pretties.append(songext)
# Rename each file from ugly to pretty.
for ugly, pretty in zip(uglies, pretties):
if __debug__:
print ugly, '-->', pretty
else:
os.rename(ugly, pretty)

So for you to use spaces, just call with something like this::

fix_ugly_song_names('/var/mp3/pop/The_Beatles/Rubber_Soul',
'The Beatles',
spacerepl=' ')

I used the __debug__ gate to allow you to just see what it will do::

$ ls -1
01 drive my car.mp3
02 norwegian wood.mp3
03 you won't see me.mp3
04 nowhere man.mp3
mvmp3.py
$ python ./mvmp3.py
01 drive my car.mp3 --> The Beatles - Drive My Car.mp3
02 norwegian wood.mp3 --> The Beatles - Norwegian Wood.mp3
03 you won't see me.mp3 --> The Beatles - You Wont See Me.mp3
04 nowhere man.mp3 --> The Beatles - Nowhere Man.mp3

And then to actually do it with the non-__debug__ path::

$ python -O ./mvmp3.py
$ ls -1
mvmp3.py
The Beatles - Drive My Car.mp3
The Beatles - Norwegian Wood.mp3
The Beatles - Nowhere Man.mp3
The Beatles - You Wont See Me.mp3

If you want to keep the `badchars` in the file names, then you will
have to do *more* work since `song.title()` won't be able to do the
work for you.

Now I need to go beautify my collection. :-)

--
_ _ ___
|V|icah |- lliott http://micah.elliott.name md*@micah.elliott.name
" " """
Oct 31 '05 #6

P: n/a
On Oct 31, Micah Elliott wrote:
Now I need to go beautify my collection. :-)


While a fun exercise, there are probably already dozens (or
thousands?) of utilities in existence that do this and much more.

--
_ _ ___
|V|icah |- lliott http://micah.elliott.name md*@micah.elliott.name
" " """
Oct 31 '05 #7

P: n/a
Micah, thanks a lot, nice script!
But its not completly working, i ran this:

fix_ugly_song_names('C:\My Shared Folder\Rubber Soul', 'The
Beatles', spacerepl=' ')

And the shell prints this:

01 drive my car.mp3 --> The Beatles - Drive My Car.mp3
02 norwegian wood (this bird has flo).mp3 --> The Beatles -
Norwegian Wood This Bird Has Flo.mp3
03 you won't see me.mp3 --> The Beatles - You Wont See Me.mp3
04 nowhere man.mp3 --> The Beatles - Nowhere Man.mp3
05 think for yourself.mp3 --> The Beatles - Think For Yourself.mp3
06 the word.mp3 --> The Beatles - The Word.mp3
07 michelle.mp3 --> The Beatles - Michelle.mp3
08 what goes on.mp3 --> The Beatles - What Goes On.mp3
09 girl.mp3 --> The Beatles - Girl.mp3
10 i'm looking through you.mp3 --> The Beatles - Im Looking Through
You.mp3
11 in my life.mp3 --> The Beatles - In My Life.mp3
12 wait.mp3 --> The Beatles - Wait.mp3
13 if i needed someone.mp3 --> The Beatles - If I Needed
Someone.mp3
14 run for your life.mp3 --> The Beatles - Run For Your Life.mp3

But the files didn't change in the folder!
Is there something mising or i'm doing something worng ??

Nov 1 '05 #8

P: n/a
Oh, forget what i've just said, i didn't read the __debug__ part.
It worked perfectly =]
Realy good Python classes!
____________________
Eduardo Figueiredo
http://dudufigueiredo.com

Nov 1 '05 #9

P: n/a
On 31 Oct 2005 10:52:27 -0800, du************@gmail.com declaimed the
following in comp.lang.python:
obs: the file names came this way(with spaces or apostrophes) from the
cd i imported.
Fancy CD, in that case... Most of mine come in as track01, track02,
etc. It is only when the ripping software accesses a CDDB system that
real titles get assigned (and the track number is an option in the
current software I have).

However...
def renme(artist, track): .... l1 = artist.title().split()
.... l2 = track.title().split()[1:]
.... return "_".join(l1 + l2)
.... fn '01 - some title.mp3' renme("the beatles", fn) 'The_Beatles_-_Some_Title.Mp3'
Or, if you are really insane... <G>
fn '01 - some title.mp3' "_".join("the beatles".title().split() + fn.title().split()[1:]) 'The_Beatles_-_Some_Title.Mp3'

-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Nov 1 '05 #10

P: n/a
On Mon, 31 Oct 2005, Micah Elliott wrote:
On Oct 31, Micah Elliott wrote:
Now I need to go beautify my collection. :-)


While a fun exercise, there are probably already dozens (or
thousands?) of utilities in existence that do this and much more.


Seconded. I initially considered writing a script to rename a huge pile of
MP3 files, but halfway through, I thought, "there's *got* to be a better
way". I found this app: http://www.softpointer.com/tr.htm

Bought it the next day. Holy crap, what a gigantic timesaver. It looks up
albums based on track lengths, downloads titles from freedb and Amazon,
does ID3 tagging, renaming, moves files into separate directories... I
busted through about 20 gigs of MP3s in three days. I kid you not.

If this is just a fun toy Python project, don't let me discourage you, but
if you have more than a handful of albums to rename, trust me. This
problem has been solved.

Here's a list of apps, including Tag&Rename, that can query freedb:
http://www.freedb.org/freedb_aware_apps.php

--
.:[ dave benjamin: ramen/[sp00] ]:.
\\ "who will clean out my Inbox after I'm dead[?]" - charles petzold
Nov 1 '05 #11

P: n/a
The best free app I've found for this is MusicBrainz [www.musicbrainz.com].

This has a huge database of obsessively correct details of albums
which can be formatted in anyway you choose. It can automatically
recognise which song an MP3 is!

This is a similar script I wrote to renumber files in sequential
order. It assumes that everything before the first underscore can be
replaced.

from path import path
import re

def renumberfiles(filesdir, startnum=1):
d = path(filesdir)
print d
x = startnum
for f in d.files():
fname = f.name.split('_', 1)
fname = str(x).zfill(2) + "_" + fname[-1]
fname = re.sub(r" ",r"_",fname)
fname = re.sub(r"__",r"_",fname)
x = x + 1
print f.name, "==>",
f.rename(f.parent + "\\" + fname)
print fname

As you can see, I use the path module rather than os.path. it's a
much more intuitive way of handling files.

http://www.jorendorff.com/articles/python/path/

Ed

On 01/11/05, Dave Benjamin <ra***@lackingtalent.com> wrote:
On Mon, 31 Oct 2005, Micah Elliott wrote:
On Oct 31, Micah Elliott wrote:
Now I need to go beautify my collection. :-)


While a fun exercise, there are probably already dozens (or
thousands?) of utilities in existence that do this and much more.


Seconded. I initially considered writing a script to rename a huge pile of
MP3 files, but halfway through, I thought, "there's *got* to be a better
way". I found this app: http://www.softpointer.com/tr.htm

Bought it the next day. Holy crap, what a gigantic timesaver. It looks up
albums based on track lengths, downloads titles from freedb and Amazon,
does ID3 tagging, renaming, moves files into separate directories... I
busted through about 20 gigs of MP3s in three days. I kid you not.

If this is just a fun toy Python project, don't let me discourage you, but
if you have more than a handful of albums to rename, trust me. This
problem has been solved.

Here's a list of apps, including Tag&Rename, that can query freedb:
http://www.freedb.org/freedb_aware_apps.php

--
.:[ dave benjamin: ramen/[sp00] ]:.
\\ "who will clean out my Inbox after I'm dead[?]" - charles petzold
--
http://mail.python.org/mailman/listinfo/python-list

Nov 1 '05 #12

P: n/a
I wrote a simpler script based in Micah Elliott's help, it's to add the
band name to mp3 files imported with iTunes:

import glob, os

def renamer_itunes(songdir, band):
""" Rename mp3 files imported from itunes, transformation:
Song Name.mp3 --> Artists - Song Name.mp3
"""
os.chdir(songdir)
archives = glob.glob("*.mp3")
pretties = []
for ugly in archives:
song, ext = os.path.splitext(ugly)
song = song.title()
song = band + " - " + song
songext = song + ext
pretties.append(songext)
for ugly, pretty in zip(archives, pretties):
os.rename(ugly, pretty)

Just an exercise, I'm begining in Python now...
Thanks to every one that helped me, i'll bring more questions for you.
Sorry for my bad english, i'm Brazilian... !
_________________
Eduardo Figueireredo
http://dudufigueiredo.com

Nov 2 '05 #13

P: n/a
On Nov 01, Dudu Figueiredo wrote:
I wrote a simpler script based in Micah Elliott's help...


I expanded my code from this thread to be a Cookbook recipe. It has
no specificity for MP3 renaming, but is generic to files with
shell-unfriendly names. It should usable as-posted if anyone needs to
cleanup a filesystem.

Any comments/improvements are appreciated.

Title: Fix ugly file names to be UNIX shell-friendly.
http://aspn.activestate.com/ASPN/Coo.../Recipe/442517

--
_ _ ___
|V|icah |- lliott http://micah.elliott.name md*@micah.elliott.name
" " """
Nov 2 '05 #14

P: n/a
du************@gmail.com <du************@gmail.com> wrote:
Ok, so the function simplifyed without loops:

def renamer(folder, band):
archive = #file to transform
rest = archive[3:]
print band + " -",rest.capitalize()
obs: the file names came this way(with spaces or apostrophes) from the
cd i imported.


Maybe you want to take a look at Jack
<http://www.home.unix-ag.org/arne/jack/>, a IMHO very nice CD ripper
written in Python.
Florian
--
Einen Troll zu füttern ist das gleiche als würde man einen Haufen
Hundescheisse sehen, absichtlich reinsteigen und sich dann beschweren.
(Christian Schneider in <20*****************@bofh.my-fqdn.de>)
Nov 22 '05 #15

P: n/a
thanks, i'll take a look ;]

Nov 22 '05 #16

P: n/a
thanks, i'll take a look ;]

Nov 22 '05 #17

This discussion thread is closed

Replies have been disabled for this discussion.