AppDividend
Latest Code Tutorials

Python With Statement Tutorial Example

0

Python With Statement Tutorial Example is today’s topic. Opening files using the with statement is generally recommended because it ensures that open file descriptors are closed automatically after program execution leaves the context of the with statement. 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 Tutorial Example

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 the 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.

 

Python With Statement Tutorial Example

Opening a file using with is as simple as: with open(filename) as the file.

Write 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.

 

Write above code using With Statement

Here notice that we have not used a file.close() function. That function will be automatically called.

Finally, Python With Statement Tutorial Example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.