为什么没有读取 .txt 列表的第一首歌曲?
Why isn't the first song of the .txt list being read?
我的 .txt 文件的第一首歌是 Knife Party - Internet Friends
第二首歌是 Galantis - Louder, Harder, Better。
但是我的代码只输出第二首歌。这是为什么?
##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
您已经逐行遍历文件行,但随后您还执行了 album.readline()
,这将丢弃上一行。不需要那个:
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()))
如果可以使用则无需关闭文件with open(...
也可以简化文件名的处理:
failinimi = input("Sisesta failinimi: ")
if failinimi in ["jukebox.txt", "80ndad.txt", "eesti_muusika.txt"]:
failinimi = "ut/" + failinimi
else:
failinimi = "ut/edm.txt"
我的 .txt 文件的第一首歌是 Knife Party - Internet Friends 第二首歌是 Galantis - Louder, Harder, Better。 但是我的代码只输出第二首歌。这是为什么?
##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
您已经逐行遍历文件行,但随后您还执行了 album.readline()
,这将丢弃上一行。不需要那个:
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()))
如果可以使用则无需关闭文件with open(...
也可以简化文件名的处理:
failinimi = input("Sisesta failinimi: ")
if failinimi in ["jukebox.txt", "80ndad.txt", "eesti_muusika.txt"]:
failinimi = "ut/" + failinimi
else:
failinimi = "ut/edm.txt"