Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read text file in python after that write something on same file

i am currently working with yolov5 code is here i slightly modified in code to save results in text file called output.txt

output.txt file :

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

After that , i wanna validate text file line by line with following conditions

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if person and tv detected in same row add status : High 
if person and laptop detected in same row add status : Low 

Expected 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

Is it possible if yes how can i resolve that

Thanks in advance

>Solution :

This code may helps you.

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading