So I've been trying to make a code that specifically changes the text in a .txt file in a certain folder - and so far it works. But there's one problem: it won't update in real time (inside the code) until I repeat the code (as in, I choose 'Y'), but when I use the script, it changes in real time outside on the file itself.
#Função
def coca():
print("Write your anotation:")
escolha = input()
arquivo1 = open('doc.txt', 'a')
arquivo1.write(escolha)
arquivo1.write(" ")
print("Your anotation:")
f = open("DOC.txt", "r")
print(f.read())
arquivo1.write("\n")
# Main
x = 0
# Loop
while x < 1:
coca()
repetir = input("Do you wish to add anything else to your annotation? Y or N ").lower()
if repetir.upper() == 'N':
print('Goodbye.')
x = x 1
Basically, say I type an anotation called "This ivory leg is what propels me, harpoons thrust in the sky" on the input, when it follows up printing the text, it shows a blank slate (if the file has nothing written on it) OR the contents of the file before I added a new anotation to it - So if I had on the .txt "Break your backs and crack your oars, men, if you wish to prevail" the "ivory leg" part wouldn't show up, until I started the code again.
I believe it's because the text will only update once the main code is finished, which means the print function only shows what's currently on the doc.txt, since the script hasn't finished yet.
Sorry for my english by the way. It's not my native language!
CodePudding user response:
Close your arquivo1 file after writing.
def coca():
print("Write your anotation:")
escolha = input()
arquivo1 = open('doc.txt', 'a')
arquivo1.write(escolha)
arquivo1.write(" \n")
arquivo1.close()
print("Your anotation:")
f = open("DOC.txt", "r")
print(f.read())
f.close()
Now this would work fine.