Python file open with statement

The 'with' statement can be used while opening a file. The advantage of with statement is that it will take care of closing a file which is opened by it. Hence, we need not close the file explicitly.

In case of an exception also, 'with' statement will close the file before the exception is handled. The format of using 'with' is:

CopiedCopy Code
with open("filename", "openmode") as fileobject:

open file with statement

A Python program to use 'with' to open a file and write some strings into the file.

CopiedCopy Code

#with statement to open a file 
with open('sample.txt', 'w') as f: 
  f.write('I am a learner\n') 
  f.write('Python is attractive\n')

file with statement example

A Python program to use 'with' to open a file and read data from it.

CopiedCopy Code

#using with statement to open a file 
with open('sample.txt', 'r') as f: 
   for line in f: 
     print(line)