我想在python文本文件中检查字符串“ rele”,如果不存在字符串,请复制文件的最后一行,然后按如下所示对其进行修改以添加为新条目。
示例: 实际文件:不存在“版本”的地方
"123456",1,0,"mher",0,"N",01Jan1986 00:00,130:00,
"123456",1,1,"ermt",0,"N",01Jan1986 00:00,100:00,
"123456",1,2,"irbt",0,"N",01Jan1986 00:00,120:00,
预期输出:
"123456",1,0,"mher",0,"N",01Jan1986 00:00,130:00,
"123456",1,1,"ermt",0,"N",01Jan1986 00:00,0:00,
"123456",1,2,"irbt",0,"N",01Jan1986 00:00,0:00,
"123456",1,3,"rele",0,"0000",01Jan1986 00:00,0:00,
该文件的最后一个条目与之前的条目相似,只是对其3,4和6列的更改很少。
我的代码:
fp = open(srcEtab.txt, 'w')
for line in lines:
if 'rele' in line:
foundRelOrPickup = True
if not foundRelOrPickup:
fp1 = open ( 'srcEtab.txt',"w" )
lineList = fp1.readlines()
new_line = lineList[len(lineList)-1]
fp1.write(new_line)
fp.close()
fp1.close()
答案 0 :(得分:0)
with open(yourFile) as f:
lines = f.readlines()
if not any(map(lambda line: "rele" in line,lines)):
last_line_words = lines[-1].split(',')
last_line_words[2] = len(lines)
last_line_words[3] = '"rele"'
last_line_words[5] = '"0000"'
lines.append(",".join([str(i) for i in last_line_words]))
with open(otherFile, "w") as f1:
for line in lines:
f1.write(line)