File Operation Example
The code is 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 write files are commonly used with write () and writelines () two functions, the difference is that
File.write (str): Writes the string str to a file
File.writelines (seq): Writes the contents of a sequence seq to a file
Both functions write data only, do not write line breaks, and if you need to wrap, manually add ' \ n ' to the end of the Str written:
NewLine characters are defined differently in each operating system, Windows line break is ' \ r \ n ', Unix/linux's newline character is ' \ n ', and Mac's line break is ' \ R ';
In Python, the line break is uniformly processed, defined as ' \ n ', when written in text mode, and if it is a Windows system, Python will automatically convert \ n to a \r\n,mac system;
Default read-write file, open operation is open in text mode: F = open (R ' D:\Python27\pro\123.bak ', ' W ')
If open in binary mode, specify parameter B:f = open (R ' D:\Python27\pro\123.bak ', ' RB ')