Python Managing File Reading with a Context Manager
In Python, a context manager is a mechanism for managing resources (such as files and network connections). Using a context manager guarantees that resources are released properly after use, even if an exception occurs. For file operations, the with statement automatically manages opening and closing the file.
Below is an example of reading a file with a context manager. We open a file, read its content and print it.
Example
Read a file with a context manager
with
open
(
'example.txt'
,
'r'
)
as
file
:
content
=
file
.
read
(
)
(
content
)
Code analysis:
with open('example.txt', 'r') as file:: When usingwithstatement opens the fileexample.txtin read-only mode ('r').fileis the file object.content = file.read(): read the whole content of the file and store it in the variablecontentit.print(content): print the file content.- When
withWhen the statement block ends, the file is closed automatically; there is no need to callfile.close()。
Output: suppose the example.txt file content is as follows:
Hello, World!
This is a test file.
After running the code, the output will be:
Hello, World!
This is a test file.
Python3 Examples