Example of a file operation
Copy Code code as follows:
#输入文件
f = open (R ' D:\Python27\pro\123.bak ')
#输出文件
FW = open (R ' D:\Python27\pro\123e.bak ', ' W ')
#按行读出所有文本
lines = 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 the two functions commonly used for writing files are write () and Writelines (), and the difference is
File.write (str): write string str to a file
File.writelines (seq): Writes the contents of the sequence SEQ all to the file
Both of these functions write only data, do not write line breaks, and, if a newline is required, manually add ' \ n ' at the end of the written Str:
Line breaks are defined differently in each operating system, and Windows newline is ' \ r \ n ', Unix/linux's newline is ' \ n ', and the Mac's newline character is ' \ R ';
in Python, a newline character is treated uniformly, defined as ' \ n ', when written in text mode, and if it is a Windows system, Python automatically turns \ nthe \r\n,mac system to resemble;
The default read-write file, open operation is opened in text mode: F = Open (R ' D:\Python27\pro\123.bak ', ' W ')
If you open in binary mode, specify the parameter b:f = open (R ' D:\Python27\pro\123.bak ', ' RB ')