File Operation example
Copy codeThe Code is as follows:
# Input file
F = open (r 'd: \ Python27 \ pro \ 123. bak ')
# Output file
Fw = open (r 'd: \ Python27 \ pro \ 123e. bak ', 'w ')
# Read all text by line
Lines = f. readlines ()
Num =-1
For line in lines:
Str = '@ SES/% I/' % num
Line = line. replace ('@ SES/1/', str)
Num = num + 1
# Writing files
Fw. writelines (line)
# Close the file handle
F. close ()
Fw. close ()
Note: write () and writelines () functions are commonly used to write files. The difference is that
File. write (str): writes the string str to the file.
File. writelines (seq): write all the content of the sequence seq to the file.
Both functions only write data and do not write line breaks. To use line breaks, manually add '\ n' to the end of the written str ':
Line breaks are defined in different operating systems. The Windows line breaks are '\ r \ n', the Unix/Linux line breaks are' \ n', And the Mac line breaks are '\ R ';
In python, line breaks are uniformly processed and defined as '\ n'. If it is written in text mode, python automatically converts \ n to \ r \ n, and the Mac system is similar;
Default read/write file, open in text mode: f = open (r 'd: \ Python27 \ pro \ 123. bak ', 'w ')
If it is enabled in binary mode, you must specify the parameter B: f = open (r 'd: \ Python27 \ pro \ 123. bak ', 'rb ')