Py学习  »  Python

如何在python中读取文本文件,然后在同一个文件中写入内容

hari prasath • 3 年前 • 1311 次点击  

我目前正在与yolov5合作,代码是 here 我稍微修改了代码,将结果保存在名为 输出txt

输出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 

预期产出:

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

如果可以,我该如何解决

提前谢谢

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/131844
 
1311 次点击  
文章 [ 1 ]  |  最新文章 3 年前
Sharim Iqbal
Reply   •   1 楼
Sharim Iqbal    3 年前

这段代码可能会对你有所帮助。

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.
    if 'person' in data[a] and 'tv' in data[a]: # Check if person and tv in the same line.
        data[a] = data[a].replace('\n','') + ' status : High\n'
    elif 'person' in data[a] and 'laptop' in data[a]:# Check if person and laptop in the same line.
        data[a] = data[a] + ' status : Low\n'

with open('result.txt','w') as file: 
    file.writelines(data) # write lines to the file.