Brendan Brendan - 3 months ago 7x
Python Question

Script writes in reverse

Sorry if I asked this wrong or formatted it wrong, this is my first time here.
Basically, this script is a very, very, simple text editor. The problem is, when it writes to a file, I want it to write:

Hi, my name
is bob.

But, it writes:

is bob.
Hi, my name

How can I fix this?
The code is here:

import time
import os
userdir = os.path.expanduser("~\\Desktop")
usrtxtdir = os.path.expanduser("~\\Desktop\\PythonEdit Output.txt")
def editor():
words = input("\n")
f = open(usrtxtdir,"a")
f.write(words + '\n')
nlq = input('Line saved. "/n" for new line. "/quit" to quit.\n$ ')
if(nlq == '/quit'):
print('Quitting. Your file was saved on your desktop.')
elif(nlq == '/n'):
print("Invalid command.\nBecause Brendan didn't expect for this to happen,\nthe program will quit in six seconds.\nSorry.")
def lowlevelinput():
cmd = input("\n$ ")
if(cmd == "/edit"):
elif(cmd == "/citenote"):
print("Well, also some help from internet tutorials.\nBut Brendan did all the scripting!")
print("Welcome to the PythonEdit Basic Text Editor!\nDeveloped completley by Brendan*!")
print("Type \"/citenote\" to read the citenote on the word Brendan.\nType \"/edit\" to begin editing.")


Nice puzzle. Why are the lines coming out in reverse? Because of output buffering:

When you write to a file, the system doesn't immediately commit your data to disk. This happens periodically (when the buffer is full), or when the file is closed. You never close f, so it is closed for you when f goes out of scope... which happens when the function editor() returns. But editor() calls itself recursively! So the first call to editor() is the last one to exit, and its output is the last to be committed to disk. Neat, eh?

To fix the problem, it is enough to close f as soon as you are done writing:

f = open(usrtxtdir,"a")
f.write(words + '\n')
f.close()   # don't forget the parentheses

Or the equivalent:

with open(usrtxtdir, "a") as f:
    f.write(words + '\n')

But it's better to fix the organization of your program:

  1. Use a loop to run editor(), not recursive calls.
  2. An editor should be writing out the file at the end of the session, not with every line input. Consider collecting the user input in a list of lines, and writing everything out in one go at the end.
  3. If you do want to write as you go, you should open the file only once, write repeatedly, then close it when done.