Open File Close File
When you open a file, you need to specify the file path and how you want to open the file, and then open it to get the file handle and manipulate it later through the file handle.
The mode of opening the file is:
- R, read-only mode (default).
- W, write-only mode. "unreadable; not exist; create; delete content;"
- A, append mode. "Readable; not exist" create; "only append content;"
"+" means you can read and write a file at the same time
- r+, can read and write files. "readable; writable; can be added"
- w+, write and read
- A +, with a
"U" means that the \ r \ n \ r \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ r or r+ mode can be converted automatically when reading
"B" means processing binary files (e.g. FTP send upload ISO image file, Linux can be ignored, Windows process binary file should be labeled)
Common operation functions
Open (file name, mode, encoding), default read-only mode F=open ('li.log') f.close ()print (F.read ()) Close (self) closes the file close (self) file descriptor Flush (self) flushes the file internal buffer next gets the next row of data readline (self, size=None Read file ReadLine (self, size=None) Read only one row of data seek (self, offset, whence=None) Specifies the pointer position of the file Tell (self): Gets the current pointer position write (self, p_str) writes the content
Third, with
To avoid forgetting to close a file after opening it, you can manage the context by:
123 |
with open ( ‘log‘ , ‘r‘ ) as f: ... |
This way, when the with code block finishes executing, the internal automatically shuts down and frees the file resource.
After Python 2.7, with also supports the management of multiple file contexts simultaneously, namely:
12 |
with open ( ‘log1‘ ) as obj1, open ( ‘log2‘ ) as obj2: pass |
File manipulation, bubbling algorithm