Python 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:
with open("filename", "openmode") as fileobject:
Python With Statement Example for File
A Python program to use 'with' to open a file and write some strings into the file.
#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')
A Python program to use 'with' to open a file and read data from it.
#using with statement to open a file with open('sample.txt', 'r') as f: for line in f: print(line)