Python file operations: line wrapping issues

Source: Internet
Author: User

Suppose a file already exists with the following content:

Mr Mr

Ms MS

Ex EX

Now you want to add a flag to the Mr Line in this file that represents the lock state, that is, the content of this flag is expected to be as follows:

Mr Lock

Ms MS

Ex EX

Rewrite the file with the following code:
User_write=[]user_read=open ("User_msg.txt", "R") for line in User_read.readlines ():    sign_user_line= Line.strip (). Split ("\ T")    if Sign_user = = Sign_user_line[0]:        line=line.strip () + "\tlock" user_ Write.append (line) User_read.close () User_write_file=open ("User_msg.txt", "W") for I in Range (0,len (user_ Write)): User_write_file.writelines (User_write[i]) user_write_file.close ()       

After writing, the file becomes

Mr Mr

Lock MS MS

Ex EX

After the investigation of the source file after each line in fact there is a return to the line, the file is rewritten, the default still exists this key value, so the change code as follows:
User_write=[]user_read=open ("User_msg.txt", "R") for line in User_read.readlines ():    sign_user_line= Line.strip (). Split ("\ T")    if Sign_user = = Sign_user_line[0]:        line=line.strip ("\ n") + "\tlock\n"  User_write.append (line) User_read.close () User_write_file=open ("User_msg.txt", "W") for I in Range (0,len ( User_write)): User_write_file.writelines (User_write[i]) user_write_file.close ()      

Python file operations: line wrapping issues

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.