"Learning Python with You Hand in Hand" 33-closing the file

In the last article "Learning Python with You Hand in Hand" 32-File Reading , we learned several ways to read files. In this article, we will learn how to close files.

When we open and use the file with open(), it is very important and necessary to explicitly close the file. If the file closing is not handled well, it may cause data loss or damage.

In fact, after reading the file in our last article, we should use the close() method to close the file, but since this part of the content was not covered at that time, there was no file closing operation, which is actually an irregular practice.

There are two ways to close the file.

1. Use close() to manually close the file

When we finish reading the open file, including the write operation to be learned later, we must use the close() method to close the file, otherwise it may cause data or file conflicts or errors.

The close() method itself is very simple, but it should be noted that when closing the file, remember to close the opened object (file_object), not the read object (file).

In [1]: path = 'lesson/text/contents.txt'
        file_object = open(path, encoding = 'utf-8')
        file = file_object.read()
        print(file.rstrip())
        file_object.close()
        file = file_object.read()   # 关闭文件后的再次读取
Out[1]: 《手把手陪您学Python》1——为什么要学Python?
        《手把手陪您学Python》2——Python的安装
        《手把手陪您学Python》3——PyCharm的安装和配置
        《手把手陪您学Python》4——Hello World!
        《手把手陪您学Python》5——Jupyter Notebook
        《手把手陪您学Python》6——字符串的标识
        《手把手陪您学Python》7——字符串的索引
        《手把手陪您学Python》8——字符串的切片
        《手把手陪您学Python》9——字符串的运算
        《手把手陪您学Python》10——字符串的函数
        ---------------------------------------------------------------------------
        ValueError                                Traceback (most recent call last)
        <ipython-input-5-90b7211a7dc0> in <module>
              4 print(file.rstrip()) 
              5 file_object.close()
        ----> 6 file = file_object.read()
        
        ValueError: I/O operation on closed file.

Like the above error, when the file is closed, it cannot be read again, and the error message also prompts that the read operation cannot be performed on the closed file.

In addition to remembering to close the file after using it, pay attention to the timing of the file closing. If we call close() in advance to close the file before we have finished using it, it may cause program errors.

Use the with keyword to avoid this situation.

2. Use with to automatically close the file

The with keyword can automatically close the file after all the programs below it have run. It can prevent us from forgetting to close the file, and it will not close the file early. It is a more recommended method of use.

The with keyword is the same as the for loop, if loop, and other keywords. You need to add a colon ":" at the end of the line where the keyword is located, and at the same time indent the code under with, so that with can know which programs and what are below When the time runs out, then close the file. After the file is closed, the code can no longer be indented, but keep the same position as with to distinguish it.

For the naming of the file object opened using the with method, you can use the as keyword, and the name of the file object is placed after as. The program is as shown in the following example, and the code read again is added to verify whether it has been automatically closed.

Since we have learned how to close the file, we will close the file in the following procedures. This is also the beginning of our good programming habits.

In the next article, we will learn several methods of file writing. Just like reading, this is also the basic principle of Python writing files, so stay tuned.

 

image

 


Thanks for reading this article! If you have any questions, please leave a message and discuss together ^_^

To read other articles in the "Learning Python with You Hand in Hand" series, please follow the official account and click on the menu selection, or click the link below to go directly.

"Learning Python with You Hand in Hand" 1-Why learn Python?

"Learning Python with you hand in hand" 2-Python installation

"Learning Python with You Hand in Hand" 3-PyCharm installation and configuration

"Learning Python with You Hand in Hand" 4-Hello World!

"Learning Python with You Hand in Hand" 5-Jupyter Notebook

"Learning Python with You Hand in Hand" 6-String Identification

"Learning Python with You Hand in Hand" 7-Index of Strings

"Learning Python with You Hand in Hand" 8-String Slicing

"Learning Python with You Hand in Hand" 9-String Operations

"Learning Python with You Hand in Hand" 10-String Functions

"Learning Python with You Hand in Hand" 11-Formatted Output of Strings

"Learning Python with You Hand in Hand" 12-Numbers

"Learning Python with You Hand in Hand" 13-Operation

"Learning Python with You Hand in Hand" 14-Interactive Input

"Learning Python with You Hand in Hand" 15-judgment statement if

"Learning Python with You Hand in Hand" 16-loop statement while

"Learning Python with You Hand in Hand" 17-the end of the loop

"Learning Python with You Hand in Hand" 18-loop statement for

"Learning Python with You Hand in Hand" 19-Summary of the first stage

"Learning Python with You Hand in Hand" 20-List

"Learning Python with You Hand in Hand" 21-Tuples

"Learning Python with You Hand in Hand" 22-Dictionary

"Learning Python with You Hand in Hand" 23-Built-in Sequence Function

"Learning Python with You Hand in Hand" 24-Collection

"Learning Python with You Hand in Hand" 25-List Comprehension

"Learning Python with You Hand in Hand" 26-Custom Functions

"Learning Python with You Hand in Hand" 27-Parameters of Custom Functions

"Learning Python with You Hand in Hand" 28-the return value of a custom function

"Learning Python with You Hand in Hand" 29-Anonymous Functions

"Learning Python with You Hand in Hand" 30-Module

"Learning Python with You Hand in Hand" 31-File Opening

"Learning Python with You Hand in Hand" 32-File Reading

For Fans: Follow the "also said Python" public account and reply to "Hand 33" to download the sample sentences used in this article for free.

Also talk about Python-a learning and sharing area for Python lovers

Guess you like

Origin blog.csdn.net/mnpy2019/article/details/111658107