First, read your file into a list. I'm assuming the format of your file is fixed: it contains
- A line specifying song name
- A line specifying genre
- A line specifying artist
- A blank line
- Repeat
Note that since there doesn't seem to be a header, you don't need the initial header = afile.readline()
Let's say you read all the lines of your file into a list called lines
lines = [line.strip() for line in afile]
# You could also do
# lines = afile.readlines()
# but that would leave behind trailing line breaks at the end of each line
Now, you know that
- Starting at the first line, every fourth line is the song name. So slice the
lines
list to take every fourth line, starting at the first line and save it as a list called songs
songs = lines[0::4]
- Do the same thing for the other information:
genres = lines[1::4]
artists = lines[2::4]
Now, we can zip()
these lists to iterate over them simultaneously, and print the songs for the artists that match the one we're looking for:
look_for_artist = "artist 2"
print(f"Songs by {look_for_artist}:")
for artist, genre, song in zip(artists, genres, songs):
if artist == look_for_artist:
print(song, genre)
# if you know that every artist has only one song, you can break the loop here since you found it already
# break
If you were doing this for a bunch of artists, I'd recommend you read the data into a dictionary (or a collections.defaultdict
) first. Then, you can look up the value of the dictionary for the given artist and this will be much faster than looping over the lists.
To account for the case when a single artist can have multiple songs, we're going to use a dictionary where the keys are the artist's name, and values are a list containing all the songs by them.
import collections
lookup_dict = collections.defaultdict(list)
for artist, genre, song in zip(artists, genres, songs):
lookup_dict[artist].append((genre, song))
Then, all you need to do is:
for genre, song in lookup_dict[look_for_artist]:
print(song, genre)
You can remove the need to read the entire file into a list and then process it into a dictionary by reading the file line-by-line in groups of four lines, but I will leave that as an exercise for you.