What is Python keyword with Statement? Simplified for beginners

In this post, we’ll be learning about python with the statement and in which tasks it can be used.

The with statements are mostly used for resources management such as writing to file or uploading files to a directory.

Syntax

with expression as variable:
    # statements

You might have seen the above block of code many times and wondered whether it is some kind of loop or statement. This issue persists with many python beginners and we are here to provide a solution for your queries.

The with statement is used for smooth execution of code even if any error has occurred inside with block the code still executes.

Table of Contents

Code Block without using ( with ) statement

Below is a simple example without using with the statement.

name = "Rahul"
age = 18
file = open("test.txt", "w")
file.write("{} is {} years old now".format(name,age))
file.close()

The above code will create a file named test.txt and writes “Rahul is 18 years old now” to the file.
After we complete processing we can safely close the file.

Writing to file using try-except error handling block

We’ll be using the python exception handling statement try-except block to catch exceptions that are occurred while writing to file.

try:
    name = "Naveen"
    age = 18
    file = open("test.txt", "w")
    file.write("{} is {} years old now".format(name,age))
except:
    print("Error has occured while processing file.")
finally:
    print("Safely closing file.")
    file.close()

#PYTHON OUTPUT
Safely closing file.

Since there is no error in our code the file writes successfully and after completion finally, a statement is executed which safely closes the file.

Now we can have the same code and knowingly we’ll make it to break just to see if it can handle errors.

try:
    name = "Ramm"
    file = open("test.txt", "w")
    file.write("{} is {} years old now".format(name,age))
except NameError as e:
    print(e)
finally:
    print("Safely closing file.")
    file.close()

#PYTHON OUTPUT
name 'age' is not defined
Safely closing file.

We have removed variable age and did assign it a value so we got an error as the name ‘age’ is not defined and after this we were successful in safely closing our file.

Using ( with ) statement

Insisted on using a try-except block we can use with a statement to safely executed our resources.

with open("test.txt", "w") as file:
    name = "Rahul"
    age = 18
    file.write("{} is {} years old now".format(name,age))
    print("File Writting process completed.")

    #PYTHON OUTPUT
    File Writting process completed.

You can see that in the same directory file test.txt is created with contents “Rahul is 18 years old now”.

Conclusion

We have come to the end of this post on What is Python keyword with Statement? Simplified for beginners. In this post, we have learned to use with statements while writing to file and also understood the importance of with statements.
If you want more information then please leave us a comment.

Related Posts

Summary
Review Date
Reviewed Item
What is Python keyword with Statement? Simplified for beginners
Author Rating
51star
1star1star1star1star
Software Name
Python Programming Language
Software Name
Windows Os, Mac Os, Ubuntu Os
Software Category
Programming Langauage