Home > Enterprise >  Why isn't the first song of the .txt list being read?
Why isn't the first song of the .txt list being read?

Time:02-25

My .txt file first song is Knife Party - Internet Friends and second song is Galantis - Louder, Harder, Better. But my code only outputs the second song. Why is that?

##5.4 Jukebox
failinimi = input("Sisesta failinimi: ")
 
if failinimi == "jukebox.txt":
    failinimi = "ut/jukebox.txt"
elif failinimi == "80ndad.txt":
    failinimi = "ut/80ndad.txt"
elif failinimi == "eesti_muusika.txt":
    failinimi = "ut/eesti_muusika.txt"
else:
    failinimi = "ut/edm.txt"
 
album = open(failinimi, encoding = "UTF-8")

järg = 1

for lugu in album:
    album_sisu = album.readline()
    while album_sisu != "":
        järg  = 1
        print("{}. {}".format(järg, album_sisu.strip()))
        album_sisu = album.readline()
album.close
>>> %Run ut.py
Sisesta failinimi: s
1. Galantis - Louder, Harder, Better

CodePudding user response:

You are already iterating over the file line, by line, but then you also execute album.readline() which will throw away the previous line. No need for that:

with open(failinimi, encoding = "UTF-8") as album:

    järg = 1

    for lugu in album:
        if lugu != "":
            järg  = 1
            print("{}. {}".format(järg, lugu.strip()))

No need to close the file if you can use with open(...

Also you can simplify the processing of the filename:

failinimi = input("Sisesta failinimi: ")
 
if failinimi in ["jukebox.txt", "80ndad.txt", "eesti_muusika.txt"]:
    failinimi = "ut/"   failinimi 
else:
    failinimi = "ut/edm.txt"

  • Related