0

The text file is formatted like so: artist, title, genre, play length, condition, stock, cost

the text file contains records of many genres which i need to add to a dictionary and count how many there are.

this is my code however when i run it, it returns 0 for each genre

def count_genres():
file = open("RECORD_DATA.txt", 'r')

rock = 0
classical = 0
pop = 0
jazz = 0
spoken_word = 0


for row in file:
    if not row[0] == "#":
        row = row.rstrip()
        row = row.split(",")
        genre = str(row[2])

        if genre == "Rock":
            rock += 1
        elif genre == "Classical":
            classical += 1
        elif genre == "Pop":
            pop += 1
        elif genre == "Jazz":
            jazz += 1
        elif genre == "Spoken Word":
            spoken_word += 1
    
print("Amount of Records in each genre ")
print("Rock: ", rock)
print("Classical: ", classical)
print("Pop: ", pop)
print("Jazz: ", jazz)
print("Spoken Word: ", spoken_word)
  • [You need to read your file not just open it](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list). – 0x263A Dec 06 '21 at 01:28

2 Answers2

0

You should try

with open("RECORD_DATA.txt", 'r') as file:
    for row in file:
        ....
Wesley Cheek
  • 1,058
  • 12
  • 22
0

Your function will fail silently if the genre isn't one of the ones in the list (e.g. if the case is wrong). Try this implementation:

def count_genres():
    genres = {genre: 0 for genre in(
        "Rock", "Classical", "Pop", "Jazz", "Spoken Word"
    )}
    with open("RECORD_DATA.txt") as file:
        for row in file:
            row = row.rstrip()
            if not row or row[0] == "#":
                continue
            genres[row.split(",")[2]] += 1

    print("Amount of Records in each genre ")
    for genre, count in genres.items():
        print(f"{genre}: {count}")

This should work correctly if the file formatting is as you say it is, but it'll raise a KeyError if it encounters a genre that's not in the list. If that's what's happening, you can decide from there how to correct it.

Samwise
  • 68,105
  • 3
  • 30
  • 44