- Python Basics
- Python Tutorial
- Python Applications
- Python Versions
- Python environment setup
- Python Basic Syntax
- Python end (end=)
- Python sep (sep=)
- Python Comments
- Python Identifiers
- Python Variables
- Python Operators
- Python Ternary Operator
- Python Operator Precedence
- Python Control and Decision
- Python Decision Making
- Python if elif else
- Python Loops
- Python for Loop
- Python while Loop
- Python break Statement
- Python continue Statement
- Python pass Statement
- Python break vs. continue
- Python pass vs. continue
- Python Built-in Types
- Python Data Types
- Python Lists
- Python Tuples
- Python Sets
- Python frozenset
- Python Dictionary
- List vs. Tuple vs. Dict vs. Set
- Python Numbers
- Python Strings
- Python bytes
- Python bytearray
- Python memoryview
- Python Misc Topics
- Python Functions
- Python Variable Scope
- Python Enumeration
- Python import Statement
- Python Modules
- Python operator Module
- Python os Module
- Python Date and Time
- Python Exception Handling
- Python File Handling
- Python Advanced
- Python Classes and Objects
- Python @classmethod Decorator
- Python @staticmethod Decorator
- Python Class vs. Static Method
- Python @property Decorator
- Python Keywords
- Python Keywords
- Python and
- Python or
- Python not
- Python True
- Python False
- Python None
- Python in
- Python is
- Python as
- Python with
- Python yield
- Python return
- Python del
- Python from
- Python lambda
- Python assert
- Python Built-in Functions
- Python All Built-in Functions
- Python print() Function
- Python input() Function
- Python int() Function
- Python len() Function
- Python range() Function
- Python str() Function
- Python ord() Function
- Python chr() Function
- Python read()
- Python write()
- Python open()
- Python Examples
- Python Examples
Python with Keyword/Statement
The with keyword or statement in Python is used to acquire some resource, and the resource gets released while leaving the with context. For example:
with open("fresherearth.txt") as fob: content = fob.read() print(content)
The snapshot given below shows the sample output produced by above Python program, demonstrating the with keyword or statement:
You're seeing this output, because in the current directory (the directory where the above Python program or source code is saved), there is a file named fresherearth.txt with the same content as displayed in the sample output. Here is the snapshot of the current directory, with opened same file, used in the sample run:
If opening mode is not provided while opening the file using open(), then by default, the file gets opened in r mode, which is for reading the file.
After leaving the with context, the file automatically gets closed. Therefore, if you try to execute fob.read() again, after the with context, then you'll see an error on output, because as soon as we exit from the with context, the file automatically gets closed. For example, the following program:
with open("fresherearth.txt") as fob: content = fob.read() print(content) print(fob.read())
produces:
But the same program can be created, without using with statement or keyword, in this way:
fob = open("fresherearth.txt") print(fob.read()) fob.seek(0) print(fob.read())
Note - The seek() function is used to move the file pointer at beginning of the file.
The output produced by above program, is:
This is because, in previous program, the with statement acquire the resource of opening the file and reading its content. Therefore, after existing from the with context, the resource gets released, therefore accessing the file using its objects named fob, produces an error saying that the file is closed. But in this program, the file is opened, until we use close() function to close the file.
A context manager is basically an object that defines the runtime context to be established when executing a with statement.
For example, the open statement is itself a context manager. It opens a file, keep the file open as long as execution is in the context of, with statement, of course, where you use it. And close it, when you leave the context, without concerning the matter, whether you've left it because of exception, or simply during the regular flow of control.
Here is another example program in Python, demonstrating the with statement:
with open("fresherearth.txt") as ifob, open("myfile.txt", "w") as ofob: for line in ifob: ofob.write(line) print("The content of 'fresherearth.txt' is copied to 'myfile.txt'")
The output is:
The content of 'fresherearth.txt' is copied to 'myfile.txt'
After executing this program, a file named myfile.txt gets created in the current directory, and the content of fresherearth.txt file gets copied into it. And if this file already exists, then its previous content gets replaced with the new content.
Python provides contextlib module that helps in constructing your own context manager, using the @contextmanager decorator. For example, the following program changes the current working directory temporarily, to work with that directory, and when the work is completed, then back to the actual current directory, for the program.
from contextlib import contextmanager import os @contextmanager def working_dir(workPath): cur_dir = os.getcwd() os.chdir(workPath) try: yield finally: os.chdir(cur_dir) with working_dir("C:/Users/DEV/jobails.com/practice"): print("The current working directory is:", os.getcwd()) # your code to work with this directory print("\nNow The current directory is:", os.getcwd())
The output is:
The current working directory is: C:\Users\DEV\jobails.com\practice Now The current directory is: C:\Users\DEV\jobails.com
where C:\Users\DEV\jobails.com is the actual current directory for the above program, because our Python program's source code is saved in this directory.
Since the directory is changed for temporary, therefore you can use your code to work with that directory. And as soon as we exit from the with construct, we get back to the original current directory. Let's create a complete practical example to demonstrate the concept:
from contextlib import contextmanager import os @contextmanager def working_dir(workPath): cur_dir = os.getcwd() os.chdir(workPath) try: yield finally: os.chdir(cur_dir) with working_dir("C:/Users/DEV/jobails.com/practice"): print("The current working directory is:", os.getcwd()) print("\nEnter the Name of File to Create: ", end="") fileName = input() fo = open(fileName, "w") print("\nThe file is created successfully.") print("Now Enter the content: ", end="") content = input() fo.write(content) print("\nThe content is written inside the file.") print("\nNow The current directory is:", os.getcwd())
Here is its sample run with user input myfile.txt as name of file, Python is Fun! as content:
I don't know how the with keyword helps in your application, but the actual working of with is the one that described above.
Note - The yield keyword similar to return except that, yield returns a generator.
After executing the above program, with same inputs as provided in above sample run. A file named myfile.txt with Python is Fun! as content will get created in that directory, used as parameter of working_dir() function, after the with keyword, instead of creating in the current directory, where the Python source code is saved.
« Previous Tutorial Next Tutorial »