Looping unlimitedly because of csvreader (solved)
Hey there I'm making a game where you have to guess the name of a song with only the first letters and if you get it wrong once you get more letters twice is game over. (Not finished) But I have run into where my reading of my song csv file doesn't end and loops forever. I have had to end it using the ^C keyboard interrupt. The code works sometimes other times it doesn't.
import random
path = __file__.replace("main.py", "")
file = open(path + "users.csv", "r+")
writer = csv.writer(file)
header = next(file)
logged = False
answer = input("Sign up or Log in? (sign/log)\n")
if answer == "sign":
username = input("Username: ")
password = input("Password: ")
answer = input("Confirm Password: ")
while answer != password:
print("Passwords do not match")
password = input("Password: ")
answer = input("Confirm Password: ")
writer.writerow([username, password, 0])
logged = True
elif answer == "log":
username = input("Username: ")
password = input("Password: ")
for line in file:
if username in line:
if password in line:
print("Hey there " + username + ", you have been logged in!")
logged = True
break
else:
print("Your password is incorrect. Please start again.")
exit()
if logged != True:
try:
print("User " + username + " is not found. Please try again or make an account.")
exit()
except:
print("Something went wrong please try again.")
exit()
file.close()
songFile = open(path + "songs.csv", "r")
csvreader = csv.reader(songFile)
header = next(csvreader)
score = 0
while True:
randomSongID = str(random.randint(1, 603))
for row in csvreader:
if randomSongID == row[0]:
randomSong = row[1]
actualSong = randomSong
artist = row[2]
randomSong = randomSong.split(" ")
for i in range(len(randomSong)):
randomSong[i] = randomSong[i][0] + (len(randomSong[i]) - 1) * "_"
print(actualSong)
randomSong = " ".join(randomSong)
answer = input(randomSong + " By " + artist+ "\n" + randomSong[0])
if answer != actualSong[1:]:
print("You have got it incorrect once. You have one more chance here is a hint.")
hint = list(actualSong[::2])
hint = "_".join(hint)
print(hint)
answer = input(randomSong[0])
if answer != actualSong[1:]:
print("The song name was:", actualSong)
print("You lost " + username + ". Your score was", score)
exit()
else:
score += 5
break
else:
score += 10
break
And this is what my terminal looks like:
~/Project/ $ python main.py
Sign up or Log in? (sign/log)
log
Username: d
Password: d
Hey there d, you have been logged in!
Just the Way You Are
J___ t__ W__ Y__ A__ By Bruno Mars
Jno
You have got it incorrect once. You have one more chance here is a hint.
J_s_ _h_ _a_ _o_ _r
Just the Way You Are
She Looks So Perfect
S__ L____ S_ P______ By 5 Seconds of Summer
Sno
You have got it incorrect once. You have one more chance here is a hint.
S_e_L_o_s_S_ _e_f_c
Sno
The song name was: She Looks So Perfect
You lost d. Your score was 5
~/Project/ $ python main.py
Sign up or Log in? (sign/log)
log
Username: d
Password: d
Hey there d, you have been logged in!
This Is How We Do
T___ I_ H__ W_ D_ By Katy Perry
This Is How We Do
^CTraceback (most recent call last):
File "/home/ubuntu/School/Project/main.py", line 55, in <module>
for row in csvreader:
File "/usr/local/lib/python3.9/codecs.py", line 319, in decode
def decode(self, input, final=False):
KeyboardInterrupt
~/Project/ $
The interrupts are where it just stopped didn't exit or anything, just went static. Any help is appreciated!
Edit: Just in case for those who need the csv file here is a sample and header.
id,title,artist,top genre,year,bpm,nrgy,dnce,dB,live,val,dur,acous,spch,pop
1,Hey, Soul Sister,Train,neo mellow,2010,97,89,67,-4,8,80,217,19,4,83
2,Love The Way You Lie,Eminem,detroit hip hop,2010,87,93,75,-5,52,64,263,24,23,82
3,TiK ToK,Kesha,dance pop,2010,120,84,76,-3,29,71,200,10,14,80
4,Bad Romance,Lady Gaga,dance pop,2010,119,92,70,-4,8,71,295,0,4,79
5,Just the Way You Are,Bruno Mars,pop,2010,109,84,64,-5,9,43,221,2,4,78
6,Baby,Justin Bieber,canadian pop,2010,65,86,73,-5,11,54,214,4,14,77
7,Dynamite,Taio Cruz,dance pop,2010,120,78,75,-4,4,82,203,0,9,77
8,Secrets,OneRepublic,dance pop,2010,148,76,52,-6,12,38,225,7,4,77
9,Empire State of Mind (Part II) Broken Down,Alicia Keys,hip pop,2010,93,37,48,-8,12,14,216,74,3,76
10,Only Girl (In The World),Rihanna,barbadian pop,2010,126,72,79,-4,7,61,235,13,4,73
This is actually due to the behaviour of the csvreader class. Once you have iterated over it once, there is nothing left inside it and so attempting to iterate over it again will yield an empty list. What you need to do is construct a list by iterating over the output and then not use the object again, as it has become essentially useless.
songFile = open(path + "songs.csv", "r+")
csvreader = csv.reader(songFile)
header = next(csvreader)
rows = [row for row in csvreader]
score = 0
while True:
randomSongID = str(random.randint(1, 601))
for row in rows:
Here is a fixed code snippet that should fix your problem