Python With: How to Use with() and open() Methods
In Python, you need to give access to the file by opening it. You can do it by using an open() function. Open returns the file object, which has methods and attributes for getting information about and manipulating the opened file.
Python With Statement
Python With Statement is used to open files. It is generally recommended because it ensures that open file descriptors are closed automatically after program execution leaves the context of the with statement.
Let’s see an example of with statement in python.
with open('app.txt', 'w') as f: f.write('AppDividend')
In the above code, we have opened up a file in write mode and written that file. With the “with” statement, you get the better syntax and exceptions handling. The “with” statement simplifies exception handling by encapsulating common preparation and cleanup tasks.
Without Python with statement
Let’s see an example where we do not use with statement and handling file operations in Python.
# app.py file = open('app.txt') data = file.read() print(data) file.close()
See the output below.
Opening a file using with is as simple as: with open(filename) as the file.
Above code using With Statement
Let’s write the same code, but using with statement and see the output.
# app.py with open('app.txt') as file: data = file.read() print(data)
The output is the same, but here we have used the with statement to read the file and printing in the console.
Here notice that we have not used a file.close() function. That function will be automatically called.
Finally, Python With Statement Example is over.