“This is the 15th day of my participation in the November Gwen Challenge. See details of the event: The Last Gwen Challenge 2021”.
IO refers to input/output in a computer. Because programs and runtime data reside in memory and are executed by the CPU, a super-fast computing core, where data is exchanged, usually on disk, network, etc., IO interfaces are required.
1. Read and write files
1.1 Reading and writing files are the most common I/O operations. Python has built-in functions for reading and writing files, which are compatible with C usage.
1.2 Before reading and writing files, you need to review the knowledge related to the operating system: The operating system provides the function of reading and writing files on disks. However, the operating system does not allow common programs to directly operate disks.
1.3 Reading and writing a file is to request the operating system to open a file object (usually called the file descriptor FDS) and then read data from the file object (read the file) or write data to the file object (write the file) through the interface provided by the operating system.
Read the file
To open a file object in file-read mode, use Python’s built-in open() function, passing in the filename and operation-mode identifier as function arguments:
2. Read and write python
Note:
“R” means read only, that is, read the file. If this parameter is not specified, this mode is used by default.
“W” means write, and write to the file as an overwrite.
“X” creates a new file, opens it, and writes to it.
“A” means to open and append the file if it exists.
“B” indicates write in binary mode.
“T” indicates the text mode text.
“+” indicates read and write.
The default value is “rt”
If the file is opened successfully, the read() method is then called to read the entire contents of the file at once.
The last step is to call the close() method to close the file. Note that the file must be closed after use. Otherwise, it is easy to misoperate the file contents without knowing where the file is offset to.