[英]How to read text file in python after that write something on same file
我目前正在使用 yolov5 代码在这里我在代码中稍作修改以将结果保存在名为output.txt的文本文件中
output.txt 文件:
0: 480x640 2 persons, 1 tv, 1: 480x640 5 persons, 1 cell phone, Done. (0.759s) Mon, 04 April 11:39:48
0: 480x640 2 persons, 1 laptop, 1: 480x640 4 persons, 1 oven, Done. (0.763s) Mon, 04 April 11:39:50
之后,我想用以下条件逐行验证文本文件
if person and tv detected in same row add status : High
if person and laptop detected in same row add status : Low
预期 output:
0: 480x640 2 persons, 1 tv, 1: 480x640 5 persons, 1 cell phone, Done. (0.759s) Mon, 04 April 11:39:48 status : High
0: 480x640 2 persons, 1 laptop, 1: 480x640 4 persons, 1 oven, Done. (0.763s) Mon, 04 April 11:39:50 status : Low
如果可以,我该如何解决?
提前致谢
此代码可能会对您有所帮助。
with open('result.txt','r') as file:
data = file.readlines() # return list of all the lines in the text file.
for a in range(len(data)): # loop through all the lines.
line = data[a]
if 'person' in line and 'tv' in line: # Check if person and tv in the same line.
data[a] = line.replace('\n','') + ' status : High\n'
elif 'person' in line and 'laptop' in line:# Check if person and laptop in the same line.
data[a] = line + ' status : Low\n'
with open('result.txt','w') as file:
file.writelines(data) # write lines to the file.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.