Python Using Context Manager to Manage File Reading

Document 对象参考手册Python3 Examples

In Python, a context manager (Context Manager) is a mechanism for managing resources (such as files, network connections, etc.). Using a context manager ensures that resources are properly released after use, even if an exception occurs during use. For file operations, usewithThe statement can automatically manage the opening and closing of files.

Below is an example of using a context manager to read a file. We will open a file, read its contents, and print them out.

Example

# Use context manager to read file
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

Code analysis:

  1. with open('example.txt', 'r') as file:: Usewiththe statement to open the fileexample.txt, and in read-only mode ('r') open.fileis the file object.
  2. content = file.read(): Read the entire contents of the file and store them in the variablecontentin.
  3. print(content): Print the contents of the file.
  4. WhenwithWhen the statement block ends, the file will be automatically closed, no need to manually callfile.close()。

Output result:example.txtThe 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 对象参考手册Python3 Examples

Other Extensions