Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python- Writing text to a file?

Tags:

python

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?

like image 772
Sandeep Singh Avatar asked Jul 18 '26 01:07

Sandeep Singh


1 Answers

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
like image 175
Jezzamon Avatar answered Jul 19 '26 13:07

Jezzamon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!