Text processing is indispensable in daily operations, suchProgramInput data preparation. With its concise and elegant syntax, python is much more efficient in text processing than compiling languages such as C ++.
File Operation example
# 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', And the Unix/Linux line breaks are' \ n ', the Mac line break is '\ R';
in Python, the line break is processed in a unified manner, defined as' \ n'. When writing in text mode, if it is a Windows system, python will automatically convert \ n to \ r \ n, similar to the MAC system;
the default read/write file is to open the file 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')