Open
1
2
3
4
5
6
7
8
9
f = open (' filename ', ' R ') # Read mode
f = open (' filename ', ' W ') # Write mode
f = open (' filename ', ' a ') # Append mode
Note: RB is read in binary
Now you think it's useless, right, I think so.
But
In the future use of the socket, the transfer of files, read and write with the binary form
RB and WB can transfer files more quickly
Read content mode
F.read () # reads the entire file at a time, the file is not applicable
F.readline () # reads only one row at a time, which accounts for small memory and slow speed
F.readlines () # Once read, the content is parsed into a list of rows that can be for...in by ... Processing
How to write files
F.write (content) # It's not going to change.
F.writeline (content) # next time will be written on the next line
Close
F.close ()
Example:
f = open (' Cdays-4-test.txt ', ' R ') #以读方式打开文件
result = List ()
For line in F.readlines (): #依次读取每行
line = Line.strip () #去掉每行头尾空白
If not Len (line) or Line.startswith (' # '): #判断是否是空行或注释行
Continue #是的话, skip not processing
Result.append (line) #保存
Result.sort () #排序结果
F.close () #关闭文件
With open (' New_file.txt ', ' W ') as FW: #with方式不需要再进行close
Fw.write ('%s '% ' \ n '. Join (Result)) #保存入结果文件
Python Training Knowledge Summary Series-Chapter III Python3 file Operations (i)