Python Text Processing

Source: Internet
Author: User

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')

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.