Rename files with numbers

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • dudufigueiredo@gmail.com

    Rename files with numbers

    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...

  • Micah Elliott

    #2
    Re: Rename files with numbers

    On Oct 31, dudufigueiredo@ gmail.com wrote:[color=blue]
    > 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
    > .[/color]

    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_M e.mp3
    [color=blue]
    > So I need to change the file number to "The Beatles -"[/color]

    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 - ', ...)
    [color=blue]
    > and Capitalize the name.[/color]

    If you avoid the apostrophe, then 'you wont see me'.title() will do
    the Right Thing.
    [color=blue]
    > I was trying to create a function and using glob and rename, but i
    > had no sucsses... Could somebody help me please,[/color]

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

    --
    _ _ ___
    |V|icah |- lliott http://micah.elliott.name mde@micah.ellio tt.name
    " " """

    Comment

    • dudufigueiredo@gmail.com

      #3
      Re: Rename files with numbers

      Ok, so the function simplifyed without loops:

      def renamer(folder, band):
      archive = #file to transform
      rest = archive[3:]
      print band + " -",rest.capitali ze()


      obs: the file names came this way(with spaces or apostrophes) from the
      cd i imported.

      Comment

      • Micah Elliott

        #4
        Re: Rename files with numbers

        On Oct 31, dudufigueiredo@ gmail.com wrote:[color=blue]
        > ...
        > obs: the file names came this way(with spaces or apostrophes) from
        > the cd i imported.[/color]

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

        #! /usr/bin/env python

        import glob, os.path

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

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

        print 'pretties:', pretties

        # rename uglies to pretties...

        --
        _ _ ___
        |V|icah |- lliott http://micah.elliott.name mde@micah.ellio tt.name
        " " """

        Comment

        • dudufigueiredo@gmail.com

          #5
          Re: Rename files with numbers

          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...

          Comment

          • Micah Elliott

            #6
            Re: Rename files with numbers

            On Oct 31, dudufigueiredo@ gmail.com wrote:[color=blue]
            > but my focus is to learn how to acess a folder and rename all files in
            > this folder.[/color]

            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_n ames(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(songdi r)
            # Shell-unfriendly characters made into a string.
            badchars = ''.join( set(string.punc tuation) - set('-_+.~') )
            # Identity table for later translation (removal of `badchars`).
            tbl = string.maketran s('', '')
            # MP3 files in `songdir` having ugly characters.
            uglies = glob.glob("*.mp 3")
            # Make some step-by-step changes to build `pretties` list.
            pretties = []
            for ugly in uglies:
            song, ext = os.path.splitex t(ugly)
            song = song.translate( tbl, badchars)
            song = song.replace(" ", spacerepl)
            song = song.title()
            song = band+spacerepl+ "-"+spacerepl+son g[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_n ames('/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 mde@micah.ellio tt.name
            " " """

            Comment

            • Micah Elliott

              #7
              Re: Rename files with numbers

              On Oct 31, Micah Elliott wrote:[color=blue]
              > Now I need to go beautify my collection. :-)[/color]

              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 mde@micah.ellio tt.name
              " " """

              Comment

              • Dudu Figueiredo

                #8
                Re: Rename files with numbers

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

                fix_ugly_song_n ames('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 ??

                Comment

                • Dudu Figueiredo

                  #9
                  Re: Rename files with numbers

                  Oh, forget what i've just said, i didn't read the __debug__ part.
                  It worked perfectly =]
                  Realy good Python classes!
                  _______________ _____
                  Eduardo Figueiredo


                  Comment

                  • Dennis Lee Bieber

                    #10
                    Re: Rename files with numbers

                    On 31 Oct 2005 10:52:27 -0800, dudufigueiredo@ gmail.com declaimed the
                    following in comp.lang.pytho n:
                    [color=blue]
                    > obs: the file names came this way(with spaces or apostrophes) from the
                    > cd i imported.[/color]

                    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...
                    [color=blue][color=green][color=darkred]
                    >>> def renme(artist, track):[/color][/color][/color]
                    .... l1 = artist.title(). split()
                    .... l2 = track.title().s plit()[1:]
                    .... return "_".join(l1 + l2)
                    ....[color=blue][color=green][color=darkred]
                    >>> fn[/color][/color][/color]
                    '01 - some title.mp3'[color=blue][color=green][color=darkred]
                    >>> renme("the beatles", fn)[/color][/color][/color]
                    'The_Beatles_-_Some_Title.Mp3 '[color=blue][color=green][color=darkred]
                    >>>[/color][/color][/color]

                    Or, if you are really insane... <G>
                    [color=blue][color=green][color=darkred]
                    >>> fn[/color][/color][/color]
                    '01 - some title.mp3'[color=blue][color=green][color=darkred]
                    >>> "_".join("t he beatles".title( ).split() + fn.title().spli t()[1:])[/color][/color][/color]
                    'The_Beatles_-_Some_Title.Mp3 '[color=blue][color=green][color=darkred]
                    >>>[/color][/color][/color]
                    --[color=blue]
                    > =============== =============== =============== =============== == <
                    > wlfraed@ix.netc om.com | Wulfraed Dennis Lee Bieber KD6MOG <
                    > wulfraed@dm.net | Bestiaria Support Staff <
                    > =============== =============== =============== =============== == <
                    > Home Page: <http://www.dm.net/~wulfraed/> <
                    > Overflow Page: <http://wlfraed.home.ne tcom.com/> <[/color]

                    Comment

                    • Dave Benjamin

                      #11
                      Re: Rename files with numbers

                      On Mon, 31 Oct 2005, Micah Elliott wrote:
                      [color=blue]
                      > On Oct 31, Micah Elliott wrote:[color=green]
                      >> Now I need to go beautify my collection. :-)[/color]
                      >
                      > While a fun exercise, there are probably already dozens (or
                      > thousands?) of utilities in existence that do this and much more.[/color]

                      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:


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

                      Comment

                      • Ed Singleton

                        #12
                        Re: Rename files with numbers

                        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(f ilesdir, 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"_",fnam e)
                        fname = re.sub(r"__",r" _",fname)
                        x = x + 1
                        print f.name, "==>",
                        f.rename(f.pare nt + "\\" + 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.



                        Ed

                        On 01/11/05, Dave Benjamin <ramen@lackingt alent.com> wrote:[color=blue]
                        > On Mon, 31 Oct 2005, Micah Elliott wrote:
                        >[color=green]
                        > > On Oct 31, Micah Elliott wrote:[color=darkred]
                        > >> Now I need to go beautify my collection. :-)[/color]
                        > >
                        > > While a fun exercise, there are probably already dozens (or
                        > > thousands?) of utilities in existence that do this and much more.[/color]
                        >
                        > 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
                        >[/color]

                        Comment

                        • Dudu Figueiredo

                          #13
                          Re: Rename files with numbers

                          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(songdi r)
                          archives = glob.glob("*.mp 3")
                          pretties = []
                          for ugly in archives:
                          song, ext = os.path.splitex t(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


                          Comment

                          • Micah Elliott

                            #14
                            File renaming recipe (was: Rename files with numbers)

                            On Nov 01, Dudu Figueiredo wrote:[color=blue]
                            > I wrote a simpler script based in Micah Elliott's help...[/color]

                            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.


                            --
                            _ _ ___
                            |V|icah |- lliott http://micah.elliott.name mde@micah.ellio tt.name
                            " " """

                            Comment

                            • Florian Diesch

                              #15
                              Re: Rename files with numbers

                              dudufigueiredo@ gmail.com <dudufigueiredo @gmail.com> wrote:[color=blue]
                              > Ok, so the function simplifyed without loops:
                              >
                              > def renamer(folder, band):
                              > archive = #file to transform
                              > rest = archive[3:]
                              > print band + " -",rest.capitali ze()
                              >
                              >
                              > obs: the file names came this way(with spaces or apostrophes) from the
                              > cd i imported.[/color]

                              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 <2005-10-25T10-04-37@bofh.my-fqdn.de>)

                              Comment

                              Working...