with keyword with example

importox

importox

Posted on June 9, 2020

with keyword with example

The Python with keyword with is a keyword in python, it is similar to the "using" statement in VB.net or/and C#.net. Keywords are case-sensitive in Python.

It creates a with-block that executes that uses the variables which are declared in the with keyword.

with keyword is used to make sure that the exit method is called when the block ends. It's like a try-except block.

If you use files in Python, you may use the with keyword for opening a file, with block may contain the file operations. And after the block execution, the file will be closed, even if there are errors.

The with keyword can be used in the shell and from a python script.

Syntax of with keyword

The syntax of the with keyword is:

        with expression [as variable]:
            with-block-statement(s)
Enter fullscreen mode Exit fullscreen mode

Python Example:

The example below uses the with keyword to write a file. This is easier than manually having to close the file.

        # opening a file and creating with-block
        with open(file_name, "w") as thefile:
            thefile.write("Hello devto!")
Enter fullscreen mode Exit fullscreen mode

data

Python example of with keyword

Use the with keyword to open a file and write the text

    # example with keyword
    # Use "with" to open and write file

    # file name
    file_name = "file1.txt"

    # open a file using with-block
    with open(file_name, "w") as thefile:
        thefile.write("Hello devto!")

    # make sure file is closed
    if thefile.closed:    
        print("File is closed")
Enter fullscreen mode Exit fullscreen mode

The program above outputs this:

File is closed
Enter fullscreen mode Exit fullscreen mode

Cotent of the file:

Hello devto!
Enter fullscreen mode Exit fullscreen mode

Related links:

💖 💪 🙅 🚩
importox
importox

Posted on June 9, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related