-4

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?

Sandeep Singh
  • 33
  • 1
  • 4
  • 2
    They do the same thing but `with` provides additional handling of errors and resource management (e.g. `close`ing files) using a context manager - please see python's documentation: https://docs.python.org/2/reference/compound_stmts.html#with – AChampion Jan 31 '16 at 22:08
  • `open()` doesn't close file. – furas Jan 31 '16 at 22:09
  • I have edited the question to make my question a little more clear. – Sandeep Singh Jan 31 '16 at 22:19

2 Answers2

0

with himself will close file and you don't need to use method close()

JRazor
  • 2,707
  • 18
  • 27
0

The first simply opens the file and assigns the object to fout. The with statement adds error handling and cleanup. If there is an error opening the file, the with block will quit, but there will be no traceback. Also, using the with statement, you don't need to close the file explicitly; it will take care of that for you. More information can be found here.

zondo
  • 19,901
  • 8
  • 44
  • 83
  • Thanks. But I had a different doubt than the one you answered, which probably wasn't very clear from my OP. Have edited the post. The problem is the way they are producing the output in the file. – Sandeep Singh Jan 31 '16 at 22:42
  • I'm sorry; I can't help you with that one. – zondo Feb 01 '16 at 20:16