1. Read the file:
F=open (' directory ', ' Read and write mode ', encoding= ' gbk,error= ' Egiong ') can not be written after three entries but the default is ' R ' read mode; The file object opened by the Open function is automatically added with the read () method;
F.read () read out the file you just opened; Finally, remember the close () function; otherwise there will be unpredictable consequences.
Read/write mode: R read-only, r+ read/write, W New (overwrites the original file), a append, b binary. Common mode. such as: ' RB ', ' WB ', ' r+b ' and so on
The ReadLine () function, which reads multiple file contents sequentially, returns a list by row. When reading, use an iteration to print(line.strip()#
remove the/N of each line
With open (' Nihaoa.txt ') as F: easy to throw with try finally exception
For I in F.readlines ():
Print (I.strip ())
2, Write file:
Open the file first, and then use the Write method, in order to prevent the absence of close () or with
With open (' Nihaoa.txt ', ' W ') as F:
F.write (' Woshidahaoren ')
Note that the Write method overwrites the original file content directly;
Python Learning note Nine-file read and write