Open (file, mode= ' R ', Buffering=-1, Encoding=none, Errors=none, Newline=none, Closefd=true, Opener=none)
Open file and return a stream. Raise IOError upon failure.
Common open Mode:
R can only read
R+ is readable and writable, does not create files that do not exist, writes from the top, overwrites content from the previous location
w+ readable writable, if the file exists, overwrites the entire file, does not exist then creates
W can only write, overwrite entire file, not exist then create
A can only be written, add content from the bottom of the file does not exist then create
A + readable writable from the top of the file add content from the bottom of the file does not exist then create??? Actually write from the beginning
Note: RB is binary read, when used to the socket, transfer files, read and write in binary form, RB and WB can be faster file transfer
1 with open (' Test.txt ', mode= ' r+ ', encoding= ' Utf-8 ') as F:2 f.read (1) 3 f.writelines ("Beijing")
============
Write operation does not automatically add line break
There is a line break at the end of the read line and you can remove the line break with the ". Strip ().
With open (' Test.txt ', mode= ' R ', encoding= ' utf-8 ') as F: For lines in F: print (Line.strip ()) Remove line break
================
If the pointer is pointing back and you want to read the previous content, you need to first point the pointer back to the front before reading.
With open (' Test.txt ', mode= ' w+ ', encoding= ' utf-8 ') as F: f.writelines ("Tianjin") f.writelines (' Shandong ') F.flush ( ) f.seek (0) print (F.readlines ())
==============
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 # Yes, skip processing result.append (line) #保存 result.sort () #排序结果 f.close () #关闭文件with o Pen (' New_file.txt ', ' W ') as FW: #with方式不需要再进行close fw.write ('%s '% ' \ n '. Join (Result)) #保存入结果文件
Python file read/write