DEV Community


Posted on

with keyword with example

The Python with keyword with is a keyword in python, it is similar to the "using" statement in or/and 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]:

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!")


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")

The program above outputs this:

File is closed

Cotent of the file:

Hello devto!

Related links:

Top comments (0)