Python exercise, C4DM Software Carpentry Mar 2013

Task

Write a program that allows a user to input a source playlist (in the same format as the example playlist attached below), a destination file, a minimum and maximum song length in the format minutes:seconds (i.e. 3:30) and a genre.

The program must write to the destination file a new playlist (in the same format as the original) of all songs in the provided playlist that fit the song length criteria and are in the required genre.

For example, the python program would be run as:

python getSongs.py fullPlaylist.txt newPlaylist.txt 1:00 2:00 Rock

This would write a file called newPlaylist.txt containing a list of all rock songs from fullPlaylist.txt that are between 1 and 2 minutes long.

Example file and implementation details

A large playlist containing randomly generated band and song names is attached below, which should be used to test the program.

You should use functions to achieve the task, and ensure that the program is fail-safe and handles user input errors gracefully.

This should be achievable with the concepts covered in the Introduction To Python workshop, but pay extra attention to how you parse each line and separate/split it by the various characters. You may need to separate entries more than once.

Recall also that strings can be concatenated simply by adding them:

>>>print 'text1' + 'text2'
>>>'text1text2'

One extra thing that is worth mentioning here is how to write to files rather than read from them. Recall the procedure for opening and reading a file:

source = open('file.txt', 'r')

We simply need to replace the 'r' flag (which stands for 'read') with 'w'

writer = open('newfile.txt', 'w')

To write something to the file we just call:

writer.write('text to be written')

If we want to write something and then go onto a new line, we must add \n to the end of the string.

writer.write('text to be written\n') 

Have fun!

Any problems?

If you run into any problems, please ask us! (Bogdan, Luis, or Chris C)

fullPlaylist.txt Magnifier - Example playlist file 8.95 KB, downloaded 266 times Chris Cannam, 2013-03-16 10:43 AM