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 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.
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 better syntax and exception handling.
The “with” statement simplifies exception handling by encapsulating standard 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.
Let’s write the same code but use 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.