There are many kinds of operations on files in Python. Common operations include create, delete, modify
permissions, read, write, etc. These operations can be roughly divided into the following
Delete and modify permissions: Acts on the file itself and belongs to system-level operations.
Write, read: These are the most common operations on files. They affect the contents
of files and belong to application-level operations.
Among them, the system-level operation function of the file is single and relatively easy to implement.
It can be implemented by using a special module (os, sys, etc.) in Python and calling a specified
function in the module. For example, suppose there is a file "a.txt" in the sibling directory of
the following code file. You can delete the file by calling the remove function in the os module.
The specific implementation code is as follows:
For file-level operations, you usually need to follow fixed steps, and the implementation process is
relatively complicated, and it is also the focus of this chapter.
The file-level operation of the file can be divided into the following 3 steps, each of which needs
to be implemented with the corresponding function:
Open a file: Use the open() function, which returns a file object;
Read / write to an open file: read the file contents using read(), readline(),
and readlines() functions; to write content to a file, use the write() function.
Close the file: After reading / writing the file, you need to close the
file. You can use the close() function.
A file must be opened before it can be operated, and after the operation is over, it should be closed.
The sequence of these 3 steps must not be disturbed.
Each function of the above operation file will be introduced in detail as a section.