Python read/Write File Operation example Program
In daily operations, text processing is indispensable, such as program input data preparation. With its concise and elegant syntax, python is much more efficient in text processing than compiling languages such as C ++, see the code below
File Operation example
Copy the Code as follows:
# Input file
F = open (r 'd: Python27pro123. bak ')
# Output file
Fw = open (r 'd: Python27pro123e. 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 'rn ', 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'. When written in text mode, if it is in Windows, python will automatically convert n to rn, mac systems are similar;
The default read/write file is opened in text mode: f = open (r 'd: Python27pro123. bak ', 'w ')
If it is enabled in binary mode, you must specify the parameter B: f = open (r 'd: Python27pro123. bak ', 'rb ')