In daily operation, without text processing, such as program input data preparation, Python by virtue of its simple and elegant syntax, in the text processing than C + + and other compiled language development efficiency of a large section, the following look at the code
The sample file operation copies the code code as follows: #输入文件 f = open (R ' D:python27pro123.bak ') #输出文件 FW = open (R ' D:python27pro123e.bak ', ' W ') #按行读出所有文本 Lin es = f.readlines () num =-1 for line in lines:str = ' @SES/%i/'%num line = Line.replace (' @SES/1/', str) num = num + 1 #写入文件 fw.writelines (line) #关闭文件句柄 f.close () fw.close () Note that there are two functions written () and Writelines () commonly used for writing files, the difference being that file Write (str): writes string str to a file file.writelines (seq): Writes the contents of a sequence seq all to a file, both of which write data, do not write line breaks, and, if you need to wrap, manually add ' n ' to the str tail that is written: Line breaks are defined in various operating systems, and Windows newline is ' RN ', Unix/linux's newline character is ' n ', and the Mac's line-feed character is ' r '; In Python, the newline character is treated uniformly, defined as ' n ', when written in text mode, and if it is a Windows system, Python automatically converts n to Rn,mac system; The default read-write file, open operation is opened in text mode: F = open (R ' D: Python27pro123.bak ', ' W ') if you open in binary mode, specify the parameter b:f = open (R ' D:python27pro123.bak ', ' RB ')