C4DMMar2013Exercise » History » Version 1
Chris Cannam, 2013-03-16 10:38 AM
1 | 1 | Chris Cannam | h1. Python exercise, C4DM Software Carpentry Mar 2013 |
---|---|---|---|
2 | 1 | Chris Cannam | |
3 | 1 | Chris Cannam | |
4 | 1 | Chris Cannam | |
5 | 1 | Chris Cannam | |
6 | 1 | Chris Cannam | Write a program that allows a user to input a source playlist (in the format of the provided playlist), 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: |
7 | 1 | Chris Cannam | |
8 | 1 | Chris Cannam | getSongs.py fullPlaylist.txt newPlaylist.txt 1:00 2:00 Rock |
9 | 1 | Chris Cannam | |
10 | 1 | Chris Cannam | 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. |
11 | 1 | Chris Cannam | |
12 | 1 | Chris Cannam | A large playlist containing randomly generated band and song names is provided with this exercise, which should be used to test the program. |
13 | 1 | Chris Cannam | |
14 | 1 | Chris Cannam | You should use functions to achieve the task, and ensure that the program is fail-safe and handles user input errors gracefully. |
15 | 1 | Chris Cannam | |
16 | 1 | Chris Cannam | 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: |
17 | 1 | Chris Cannam | |
18 | 1 | Chris Cannam | >>>print 'text1' + 'text2' |
19 | 1 | Chris Cannam | >>>'text1text2' |
20 | 1 | Chris Cannam | |
21 | 1 | Chris Cannam | 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: |
22 | 1 | Chris Cannam | |
23 | 1 | Chris Cannam | source = open('file.txt', 'r') |
24 | 1 | Chris Cannam | |
25 | 1 | Chris Cannam | We simply need to replace the 'r' flag (which stands for 'read') with 'w' |
26 | 1 | Chris Cannam | |
27 | 1 | Chris Cannam | writer = open('newfile.txt', 'w') |
28 | 1 | Chris Cannam | |
29 | 1 | Chris Cannam | To write something to the file we just call: |
30 | 1 | Chris Cannam | |
31 | 1 | Chris Cannam | writer.write('text to be written') |
32 | 1 | Chris Cannam | |
33 | 1 | Chris Cannam | If we want to write something and then go onto a new line, we must add \n to the end of the string. |
34 | 1 | Chris Cannam | |
35 | 1 | Chris Cannam | writer.write('text to be written\n') |
36 | 1 | Chris Cannam | |
37 | 1 | Chris Cannam | Have fun! |