In previous chapters, we have been using the close function to manually close files opened with the open function. This section talk about close function.
The close function is specifically used to close an opened file, and its syntax is simple, as shown below:
file.close()
Where file represents an open file object.
The reader may always have such a question, that is, must the file closed using the open function be called after the operation is completed? The answer is yes. After the file is opened and the operation is completed, it should be closed in time, otherwise problems may occur in the running of the program.
For example, analyze the following code:
import os f = open("a.txt",'w') os.remove("a.txt")
In the code, we introduce the os module and call the remove function in this module. The function of this function is to delete the specified file. However, if you run this program, the Python interpreter reports the following error:
Obviously, because we used the open function to open the a.txt file, but did not close it in time, it directly caused errors in subsequent remove functions. So the correct procedure would look like this:
import os f = open("a.txt",'w') f.close() os.remove("a.txt")
When it is determined that the a.txt file can be deleted, run the program again and you can find that the file has been successfully deleted.
As another example, if we do not call the close function to close an open file, it is determined that the operation of reading the file will not be affected, but it will cause the write or writeline function to write data to the file, and the write fails. Example:
f = open("a.txt", 'w') f.write("www.freelearningpoints.com")
The output is:
26
After the program was executed, although the Python interpreter did not report an error, opening the a.txt file found that it was not successfully written at all.
This is because when writing data to a file opened in text format instead of binary format, for efficiency reasons, Python first temporarily stores the data into a buffer, and only closes the file using the close function when the data in the buffer is actually written to the file.
Therefore, add the following code at the end of the above program:
f.close()
Example:
f = open("a.txt", 'w') f.write("www.freelearningpoints.com") f.close()
The output is:
26
Open the a.txt file, you will find that the string has been successfully written to the file:
More Tutorials:
Python Installation - Linux (Ubuntu)More Python Exercises:
Python String Exercises