Home > Net >  Trying to append new text to a text file rather than overwriting it in a while loop
Trying to append new text to a text file rather than overwriting it in a while loop

Time:04-02

I am relatively new to python and have been working on a simple program that allows the user to view, edit and create new text files. The option I am currently focusing on is creating new text files. The program asks the user various questions, which are then inputted in the text file.

Currently what I am stuck on is, I am trying to technically "list" a bunch of inputs into the text file. So, say the question would be outputted such as:

Enter the amount of dog breeds you could think of:

(USER INPUT)
Jack Russel
(PROGRAM INPUT)
Done? (Y/N)
(USER INPUT)
N
(PROGRAM INPUT)
Continue.
(USER INPUT) 
Chihuahua
(PROGRAM INPUT)
Done? (Y/N)
(USER INPUT)
Y
[FINISH]

I have tried to do this by implementing a while loop to ask the user whether they are done or not, and although this works, whenever the user inputs another input, it will overwrite the first one in the text file rather than adding a completely new one. Is there a neat, compact way of doing this, or do I have to create a new function for every "dog breed" that the user inputs?

Code:

        keepGoing = True
        while keepGoing == True:
            dogb = input("Enter a dog breed: ")
            dogc = input("Enter the dog colour: ")
            dogn = input("Enter the dog name: ")
            dogmale = input("Are they male? ")
            complete = False 
            while complete == False:
                done = input ("DONE? (Y/N): ")
                if done == "Y":
                    keepGoing = False
                    complete = True
                elif done == "N":
                    keepGoing = True
                    complete = True
                else:
                    print ("Invalid Option")
        
        createFile.write("\n"   "Dog Breed: "   dogb   '\n'   "Dog colour: "   dogc   '\n'   "Dog name: "   dogn   " (Male? "   dogmale   ")")

So currently, when my program is run, the user will be prompted with those 4 questions. Once they answer all 4, it will be stored as 4 separate lines in a text file. However, if the user inputs that they are NOT done, implying they want to add another dog breed, it will ask those 4 questions again like I want it to, but when they are answered, it will just overwrite the first inputs. I want to make it so that, if the user inputs that they are not done, when they answer the 4 questions again, it will add another 4 lines of text for the new dog breed they added, until the user inputs "Y" for done, which will stop the loop and continue the program.

I am not sure what to do other than making completely new functions for every single dog breed, but I am sure there is a better, neater way of doing so. Any help would be greatly appreciated, thanks!

EDIT: I would assume it has something to do with appending the new data that I added to the text file rather than overwriting it. I am having this issue in the first place because I am not sure how to open the file, since I am creating a new one from scratch using this code:

        save_path = 'D:/My project/users/'
        name_of_file = input("What do you want to name the file? ")
        completeName = os.path.join(save_path, name_of_file ".txt")         
        createFile = open(completeName, "w")
        referenceName = input("Enter the name of the dog (e.g. Homer Simpson): ")

and then the data is written to the text file using:

myfile.write(referenceName) etc

 

CodePudding user response:

Here is your updated code

keepGoing = True
while keepGoing == True:
    dogb = input("Enter a dog breed: ")
    dogc = input("Enter the dog colour: ")
    dogn = input("Enter the dog name: ")
    dogmale = input("Are they male? ")
    complete = False 
    while complete == False:
        done = input ("DONE? (Y/N): ")
        if done == "Y":
            keepGoing = False
            complete = True
        elif done == "N":
            keepGoing = True
            complete = True
        else:
            print ("Invalid Option")
        with open("test.txt", "a") as myfile:
            myfile.write("\n"   "Dog Breed: "   dogb   '\n'   "Dog colour: "   dogc   '\n'   "Dog name: "   dogn   " (Male? "   dogmale   ")")

CodePudding user response:

I'm not sure just how new to Python you are, but a common newbie mistake that creates this exact situation is opening the file with w instead of a.

CodePudding user response:

Points to take care of

  1. Opening a file- you should do it using open it creates the file if doesnot exists and then closes the file.
with open('file.txt', 'w') as f:
    f.write("hello world")

  1. In order to take multiple inputs you should have someway(data-structure) to store the value. - list

Updated Solution

keepGoing = True
dogs = [] #added a list, which will store all different inputs, 
while keepGoing == True:
    dogb = input("Enter a dog breed: ")
    dogc = input("Enter the dog colour: ")
    dogn = input("Enter the dog name: ")
    dogmale = input("Are they male? ")
    complete = False 
    dogs.append({"dogb": dogb, "dogc": dogc,"dogn":dogn, "dogmale": dogmale}) # dictionary, which is appended to list
    # so now, in a list each index has data of a dog. So now as many inputs can be handled.
    while complete == False:
        done = input ("DONE? (Y/N): ")
        if done == "Y":
            keepGoing = False
            complete = True
        elif done == "N":
            keepGoing = True
            complete = True
        else:
            print ("Invalid Option")
with open('file.txt', 'w') as f:
    f.write("hello world")
    for dog in dogs: #iterating over the list to write the list to file.
        f.write("\n"   "Dog Breed: "   dog["dogb"]   '\n'   "Dog colour: "   dog["dogc"]   '\n'   "Dog name: "   dog["dogn"]   '\n' " (Male? "   dog["dogmale"]   ")"   '\n')
# createFile.write("\n"   "Dog Breed: "   dogb   '\n'   "Dog colour: "   dogc   '\n'   "Dog name: "   dogn   " (Male? "   dogmale   ")")
  • Related