hlep: a text search and rename question

James Stroud jstroud at mbi.ucla.edu
Mon Jan 12 12:13:25 CET 2009


sensen wrote:
> matter description:
> 
> when a use an tools to do the ape to flac convert, i can use the cue
> file attached with ape, but the problem is the converted flac file
> don't name by the title in the cue file but like Track_1.flac,
> Track_2.flac ... , so i want to write a script to do this work, system
> is xp sp2, the python is 2.44, i have a plone site in this computer,
> that is why i want to use python to do this work.
> 
> so simplify and example
> 
> CDImage.cue, Track_1.flac, Track_2.flac, Track_3.flac, Track_4.flac
> all above files in the same folder.
> 
> the cue file is just a text file like bellow:
> 
> 
> PERFORMER "Dido"
> TITLE "Life For Rent"
> FILE "Dido - Life for Rent.ape" WAVE
>   TRACK 01 AUDIO
>     TITLE "White Flag"
>     PERFORMER "Dido"
>     INDEX 01 00:00:00
>   TRACK 02 AUDIO
>     TITLE "Stoned"
>     PERFORMER "Dido"
>     INDEX 00 04:00:03
>     INDEX 01 04:01:45
>   TRACK 03 AUDIO
>     TITLE "Life For Rent"
>     PERFORMER "Dido"
>     INDEX 00 09:56:47
>     INDEX 01 09:56:53
>   TRACK 04 AUDIO
>     TITLE "Mary's In India"
>     PERFORMER "Dido"
>     INDEX 01 13:37:57
> 
> the things i want to do
> 
> 1. search the current folder cue file (only one cue file) contents.
> find the     TITLE "White Flag" and get the White Flag and maybe we
> can save it to a var.
> 2. then rename the Track_1.flac to the White Flag.flac
> 3. search the next title TITLE "Stoned" and save ti to var.
> 4. then rename the Track_2.flac to the Stoned.flac.
> 5. do the same things to the end title.
> 
> someone can give some outline, or code is more wonderful.  thanks in
> advance.

This isn't much work in python:

import os, glob, re
cue = iter(open('CDImage.cue').readlines())
titles = []
for line in cue:
   if line.strip().startswith('FILE'):
     break
for line in cue:
   if line.strip().startswith('TITLE'):
     titles.append(line.split('"')[-2])
flacs = glob.glob('*.flac')
flacs.sort(key=lambda f: int(re.search(r'\d+', f).group(0)))
for old, new in zip(flacs, titles):
   os.rename(old, new)


There is no error checking for properly formatted cue file, etc.

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com



More information about the Python-list mailing list