Python- Writing text to a file?

There is only one type of file object, just two different ways to create one. The main difference is that the with open("abc.txt",a) as fout: line handles closing the files for you so it’s less error prone.

What’s happening is the files you create using the fout=open("abc.txt",a) statement are being closed automatically when the program ends, and so the appending is only happening then.

If you the run the following code, you’ll see that it produces the output in the correct order:

f = open("abc.txt", 'a')
f.write("Step 1\n")
f.close()
with open("abc.txt", 'a') as fout:
   fout.write("Step 2\n")

The reason the lines became reversed is due to the order that the files were closed. The code from your first example is similar to this:

f1 = open("abc.txt", 'a')
f1.write("Step 1\n")

# these three lines are roughly equivalent to the with statement (providing no errors happen)
f2 = open("abc.txt", 'a')
f2.write("Step 2\n")
f2.close() # "Step 2" is appended to the file here

# This happens automatically when your program exits if you don't do it yourself.
f1.close() # "Step 1" is appended to the file here

Leave a Comment