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