File operation is also a very important operation process in Python development. In this article, I will summarize some basic operations in file operation.
1. File open (open)
- read (r): read-only, cannot be written after opening, an error will be reported if the file does not exist when opening .
- write (w): Write only, it cannot be read after opening and can only be written. When writing and opening, the original file content will be cleared first. If the file content does not exist, a new one will be added.
-Append (a): Can only append, not read. Append new content to the original content. If the file content does not exist, a new one will be added.
-Writing specifications
file_object=open(,mode=,encoding=") file_object.append("填要追加的内容")
- r : Readable and writable.
- Read: Start reading from position 0 by default, you can also adjust the cursor position through seek.
- Write: Write based on the current cursor position, Other text may be covered, and the cursor position can be adjusted through seek.
- w :
- Reading: The default cursor is always at the end or 0, and the cursor position can be adjusted through seek when reading.
-Write: The file will be cleared first when writing.
-a :
-Read: The default cursor is always at the end. After adjusting the cursor position through seek, then When reading and appending, the cursor automatically jumps to the end.
- Write: Always write at the end.
2. File operation
- Read:
- read() : Read all the content into the memory. Too much content may cause crash
- read() : Write characters in brackets, read several times backward from the current cursor position characters.
- readlines(): All files are read into the memory and divided into lists according to each line. \nLine breaks are not displayed in the file. , there is a newline character after the actual newline
- write
3. File close
- file_object.close(): The content will be forced when closing Save to hard disk
[Recommended course: Python video tutorial]
The above is the detailed content of [Python Learning] File Operation. For more information, please follow other related articles on the PHP Chinese website!