Python Text File Input Bug

Viewed 67

So, I am writing a program that, when I input a text, it writes it in a text file. The first problem I had was that it was overwriting itself every time I input something. What I want is so it would create a new line every time I input something.

textinput= "\TextInput: "
inputtext = input(textinput)

with open("Text Input.txt", "w") as f:
    for text in inputtext:
        f.write(text)

I fixed this problem by addingf.write("\n") in the for loop. The problem is, that in a for loop, it would keep repeating itself for every letter. Putting it outside of the for loop doesn't work, and keeps rewriting itself, like it used to. Is there any solution to this?

3 Answers

I think the simplest should be

with open("test_input.txt", "a") as ff:
    print(input("Text Input: "),file=ff)

No ned for \n and so on if you just use print(,file=)

You don't need to write per character into the file. You can write an entire line at once.

Please use the append flag "a" instead of the write flag "w" to fix your problem.

This should solve your problem:

textinput= "\TextInput: "
inputtext = input(textinput)
inputtext += "\n"

with open("Text Input.txt", "a") as f:
    f.write(inputtext)

ofcourse it overwrite so you have to use append a instead of using write w as an argument

 textinput= "\TextInput: "
           inputtext = input(textinput)

 with open("Text Input.txt", "a") as f:
    for text in inputtext:
         f.write(text)
Related