简体   繁体   中英

Python- Writing text to a file?

I am trying to learn python and wanted to write some text to a file. I came across two kind of file objects.

fout=open("abc.txt",a)

with open("abc.txt",a) as fout:

The following code:

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

Gave the output:

Step 2
Step 1

And the following code:

f= open("abc1.txt", 'a')
f.write("Step 1\n")
f= open("abc1.txt", 'a')
f.write("Step 2\n")

Gave the output:

Step 1
Step 2

Why is there difference in the outputs?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM