I am trying to figure out a way to store songdata as a list in a .txt. The method I am using seems to be storing the values somewhere, but its not writing them to the file. I also am trying to insert a loop into it so I can keep entering "songs" instead of only one. I haven't used classes before and I cant quite grasp how it would be done. I maybe am going about it wrong and need to reformat parts? Any advice would be awesome.
class Song:
def __init__(self,song,chart,member):
self.song = song
self.chart = chart
self.member = member
def __str__(self):
return self.song + " topped the charts at " + str(self.chart)+ " band memebers include " + str(self.member)
songdata = Song(input("song"),input("chart spot"), input("bandemember"))
def readstring(f, line):
string = line.strip('\r\n')
return string
def writestring(f, string):
f.write(string)
with open("string.txt", "a+", encoding="utf-8") as f:
cont = "Y"
while cont.upper() == "Y":
d = input(songdata)
if d != "q":
string = " "+d
writestring(f, string)
else:
print("saving.....")
break
f.seek(0)
for line in f:
print(readstring(f,line))
f.close()
Couple of notes:
d = input(songdata)
, the prompt from input
will always display the same thing after the first time.d=...
is always blank from the user. You requested the song information when you initialised the class (which you only did once), but never wrote that to file (instead you wrote f.write(string)
, where string=" "+d
)write()
method.I've re-written some of your code (the writing to file parts) below. I assumed you wanted the user to be able to exit the program at any time by entering in the key sequence q
, and have done so accordingly. You can make something more nifty with generators I believe, but this isn't related to the problem:
class Song:
"""
song class
"""
def __init__(self, song, chart, member):
self.song = song
self.chart = chart
self.member = member
def __str__(self):
return (self.song
+ " topped the charts at "
+ str(self.chart)
+ " band memebers include "
+ str(self.member)
+ '\n'
)
def main():
with open("string.txt", "a+", encoding="utf-8") as fd:
#Loop until user requests to stop
#Key sequence to stop = 'q'
while(1):
#Get user input
prompt = ">>\t"
in_song = input("song" + prompt)
if (in_song == 'q'):
break
in_chart_spot = input("chart spot" + prompt)
if (in_chart_spot == 'q'):
break
in_band_mem = input("band members" + prompt)
if (in_band_mem == 'q'):
break
#Create the class
song_data = Song(in_song, in_chart_spot, in_band_mem)
#Write out the data
fd.write(str(song_data))
if __name__ == '__main__':
main()
Hope this helps :)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments