##open将操作系统发起请求, the operating system completes the request,#f = open (' Old.txt ', ' r ', encoding = ' utf-8 ')#res = F.read ()#Print (res)#f.close ()#f = open (' Old.txt ', ' r ', encoding = ' utf-8 ')#res = F.readline () # #读取一行#Print (res)#f.close ()##读完文件之后必须要关闭, otherwise the file will remain in the operating system##执行以下操作可以在打开文件之后, automatically close the file#With open (' Old.txt ', ' r ', encoding = ' utf-8 ') as F:#res = F.read ()#Print (res)#Pass#f = open (' Old.txt ', ' w ', encoding = ' utf-8 ')#f.write (' 111\n ')#f.write (' 222\n ')#f.writelines ([' a\n ', ' b\n ', ' c\n ']) # #表示的是可以写入多行#f.close ()
Mode of File Open
Open mode |
Execution mode |
' R ' |
Open a file as read-only (default) |
' W ' |
Open the file as written to overwrite the existing file |
' X ' |
If the file already exists, using this mode throws an exception |
A |
Open in write mode, append at the end if the file exists |
' B ' |
Open a file in binary mode |
' t ' |
Open in text mode (default) |
+ |
Readable writable mode (can be added to other modes) Universal line break support |
U |
Universal Line break support |
Methods for File objects
Methods for File objects |
Perform actions |
Close () |
Close File |
Read (Size=-1) |
Reads a size character from a file, and reads all the remaining characters when no size or given negative value is given. Then return as a string |
ReadLine () |
Reads a whole line of string from a file |
Write (str) |
Writes a string str to a file |
Writelines (seq) |
Want the file to be written to a string sequence seq,seq should be an iterative object that returns a string |
Seek (Offset,from) |
Move the file pointer in a file, offset from the from offset byte |
Tell () |
Returns the current position in the file |
There are many ways to read a file, you can use the read () and ReadLine () methods of the file object, or you can read directly from list (f) or directly using iterations. Read () reads in bytes, and if you do not set a parameter, it is all read, the file pointer points to the end of the file, and the tell () method tells you where the current pointer is.
Python develops "article xxx" basic file operations----and persistent storage