"Note": The following procedures are combined with a variety of network methods, and then their own practice results. Written here, the main purpose is to deepen memory, but also hope to help the post-comer
The reading and writing of files in Python consists of three steps: Opening the file, reading/writing the file, and closing the file. The file must be turned off after it is opened, because the ability to read and write files on disk is provided by the operating system, the files as objects, the operating system's resources are opened, and the operating system has a limited number of open files at the same time.
Open File:
F=open (' path/filename ', ' read/write format ', ' Encoding ', ' Error handling ')
For example:
F=open ('/users/noiccy/desktop/pythoncode/test.txt ', ' R ', encoding= ' UTF-8 ', errors= ' ignore ')
Interpretation: Read the way to open the encoding UTF-8 text file, encountered illegal then put the character, ignored
The second parameter: reads the text file with ' R ', reads the binary file with ' RB ', writes the text file with ' W ', writes the binary file with ' WB ', appends the file with ' a ', the second parameter does not write, the default is ' R '.
Read the file:
F.read () #一次性读取文件的全部内容
F.readline (n) #最多读取n个字节的内容
F.readlines () #一次读取文件的全部内容 and return to list by row
Write file:
F.write (' write content ') #一次性全部写入指定文件, if the second argument in open () is ' a ', the program appends to the end of the document the content to be written
To close a file:
F.close ()
Using the WITH statement, Python can automatically call the close () method
With open ('/users/noiccy/desktop/pythoncode/test.txt ', ' R ') as F:
print (F.read ())
With open ('/users/noiccy/desktop/pythoncode/test.txt ', ' a ') as F:
f.write (' written content ')
Read pictures:
Import pil. Image as image with
image.open ('/users/noiccy/desktop/pythoncode/thumb.jpg ') as Pic:
pic.show ()
Invoking the Write () function in an interactive environment will have a return value, which is the length of the character being written to the file.
Reference Link: https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/ 001431917715991ef1ebc19d15a4afdace1169a464eecc2000