This article is participating in Python Theme Month. See the link to the event for more details

Retrospective review

There are two types of file types: text file and binary file.

File related modules have IO, OS, CV and other modules roughly understand.

We also know that there are three steps to manipulating a file

  1. Create the file object and open the file
  2. Perform operations such as reading and writing files
  3. After the file operation, close the file

Since the underlying file is operated by the operating system, the Python interpreter must close the file object after operating on it.

Therefore, Python file closing streams provide two methods:

  • The close() method, the general and exception mechanism finally ensures that the file is closed properly
  • With file manager

The close() method in combination with the finally mechanism can also handle exceptions, but the code is very redundant

It is recommended to use the with statement in addition to the more elegant syntax, but also to handle the context generated exceptions

1. The close () method

The close() method is one of the IO class (module) methods.

The close() method is used to close an open file.

The details of file closing are as follows:

  1. No more read or write operations can be performed on the closed file. Otherwise, ValueError will be triggered
  2. The close() method allows multiple calls
  3. When a file object is referenced to another file, Python automatically closes the previous file object
  4. Get used to closing files after file operations and avoid any exceptions at all times

The close() method syntax is as follows:

File object. close();Copy the code

Let’s look at the Close method in the Python interpreter

As you can see, close() returns None

Let’s take a look at 🌰 :

f = open("JueJing.txt","a")
s = "JueJing Python"
f.write(s)
f.close()

Copy the code

As we can see from the above example, the process has four steps:

  1. Create the file object and open the file juejing.txt
  2. Write the string “JueJing” to the file
  3. If there are no problems with the program, the file is closed successfully
  4. If the program is abnormal, our OS can not close the file, this time has been occupying system resources

In order to resolve the exception in step 4 and to close the file normally, we can use the exception mechanism finally learned earlier

Optimize the above code as follows

try:

    f = open("JueJing.txt","a")
    s = "JueJing Python"
    f.write(s)
except BaseException as e:
    print(e)
finally:
    f.close()

Copy the code

2. With file management

The context_expression syntax of the with statement is used to create a resource that can be automatically closed.

With context expression [as target(s)]: with code blockCopy the code

There are two main ways that objects that support the Context Management Protocol can do this

  • __enter__()
  • __exit__()

Context Manager: An object that supports the Context management protocol, which implements __enter__() and __exit__() methods.

  • The context manager defines the runtime context to be established when the with statement is executed
  • Is responsible for performing entry and exit operations in the context of the with statement block.
  • The context manager is usually invoked using the WITH statement, but can also be used by calling its methods directly.

Runtime context: Created by the context manager, implemented through its __enter__() and __exit__() methods.

  • __enter__() Method enters the runtime context before the body executes
  • __exit__()Exits from the runtime context after the body of the statement has finished executing

Context Expression: The Expression followed by the keyword with in the with statement that returns a Context manager object.

With-body: The block of code wrapped in a with statement that calls the context manager’s __enter__() method before executing the body and __exit__() after executing the body.

Let’s rewrite the first section using finally as a with statement, as follows

with open("JueJing.txt","a") as f:
    
    s = "JueJing Python"
    f.write(s)

Copy the code

The with statement is much cleaner and more elegant than using finally code

The Python interpreter displays the following results:

Print juejing. TXT file

conclusion

Today, we’ll look in detail at two ways files can close streams: the close() method and the with method. Let us better choose to use in daily work, just as the so-called “know it” should also “know its why”

The above is the content of this issue, welcome the guidance of the big guys, see you next time ~