假设一个文件已经存在,内容如下:
mr mr
ms ms
ex ex
现在要给这个文件中的mr一行加入一个标志,代表锁定状态,即期望加上此标志的内容如下:
mr mr Lock
ms ms
ex ex
使用如下代码对文件进行重写:
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()
写完以后文件却变成了
mr mr
Lock ms ms
ex ex
后经排查得知源文件每行后面其实都有一个回车键进行换行操作,对文件进行重写时,默认仍旧存在此键值,因此更改代码如下就正常了:
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()