Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Managing File Reading with a Context Manager

Python Managing File Reading with a Context Manager

Document Object Reference Manual Python3 Examples

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

(

)

   

print

(

content

)

Code analysis:

  1. with open('example.txt', 'r') as file:: When using with statement opens the file example.txtin read-only mode ('r').file is the file object.
  2. content = file.read(): read the whole content of the file and store it in the variable content it.
  3. print(content): print the file content.
  4. When with When the statement block ends, the file is closed automatically; there is no need to call file.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.

Document Object Reference Manual Python3 Examples