A common way to work with files in Python is to create file handler with “open” statement and work with the file. After finishing the work with the file, we need to close the file handler with close statement. For example, if we want to read all lines of a file using Python , we use
fh = open(filename,'r') all_lines = fh.readlines() fh.close()
Often, it is hard to remember to close the file once we are done with the file. Python offers an easy solution for this. We can use with statement in Python such that we dont have to close the file handler. Here is an example using with statement to read all lines of a file.
with open(filename,'r') as fh all_lines = fh.readlines()
We also use with statement to open more than one file. Here is an example of using with statement in Python to open one file for reading and another file for writing.
with open(in_filename) as in_file, open(out_filename, 'w') as out_file: for line in in_file: ... ... out_file.write(parsed_line)
Want to know more about the with statement in Python, check out this blog post