Loop in a class and writing to a txt file

alienmode

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()
Jamie Phan

Couple of notes:

  • Because you only initialised the class once when you request the information from you user in the code d = input(songdata), the prompt from input will always display the same thing after the first time.
  • The reason why nothing is being written to file is probably because the response from 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)
  • As mentioned in the replies, you don't really need a specific function to write to file when you can just call the file descriptors 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.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Function not writing to txt file

From Dev

writing a list to a txt file in python

From Dev

Selenium - writing values to a .txt file

From Dev

Writing to .txt file in columns with php

From Dev

Writing big dataframe into txt file

From Dev

Writing to txt file using variables

From Dev

Writing a txt file to mySQL database

From Dev

Systemd script not writing into a .txt file

From Dev

Reading from a text file into a vector of objects in a class- writing in another txt file

From Dev

Why can't i use a while loop for writing something in a txt file

From Dev

For Loop with txt file

From Dev

Unidentified text in txt file while writing using class object in C++

From Dev

writing lines into text file with loop

From Dev

continuously writing to csv file in a loop

From Dev

Writing Array to txt file with requested name

From Dev

Writing variables to new line of txt file in python

From Dev

VB.Net Writing to Txt File

From Dev

C# Writing debug output to .txt file

From Dev

In need of JavaFX help writing to a .txt file

From Dev

Writing to a TXT file using BufferedWriter - Java

From Dev

List being shortened when writing it to a txt file

From Dev

Writing an ArrayList with different variables to a .txt file

From Dev

Writing lines to .txt file c++

From Dev

Writing to txt file in Java projects folders

From Dev

Counter reading and writing to a txt file - vbscript

From Dev

Writing text to txt file in python on new lines?

From Dev

Writing to the previous line of a txt file in Python 3.3

From Dev

saving/writing time to txt file in C++

From Dev

In need of JavaFX help writing to a .txt file