Compare multiple lines in a text file using python

2024/11/18 15:32:07

I'm writing a program that is time tracking report that reports the time that was spent in each virtual machine, I`m having a problem comparing the txt file cause the only thing that changes are the numbers and the hour that each virtual machine was used(that's why I dont Know how to compare them)

09:43:04> --- virtual Desktop 212:37:20> --- virtual Desktop 623:07:00> --- virtual Desktop 123:07:07> --- virtual Desktop 223:07:09> --- virtual Desktop 312:59:04> --- virtual Desktop 113:41:53> --- virtual Desktop 513:47:09> --- virtual Desktop 3def main():f = open("/home/lucasfernandes/Desktop/work/DGNET/logthatmatter.txt", "r")line = f.readline()x = "Desktop"while line:startime=""#print(line)line = f.readline()#print(line)if "--- Taskbarbuttons auf Desktop " in line:print(line [41:42])#startime = datetime.strptime(line[0:8], '%H:%M:%S')#print(startime)#print(line)else:if line[41:42] == "6":print(line)f.close()

the expected result is

you spent this time on virtual desktop 2: variable

but I don't know how to compare line by line of the txt file

Answer

I would read full file and create list with all lines and then get only hour and desktop number from every line.

And then I can use zip(lines, lines[1:]) to have pairs of lines to compare and calculate time between both values

import datetime# read full file
#text = open(filename).read()text = '''09:43:04> --- virtual Desktop 212:37:20> --- virtual Desktop 623:07:00> --- virtual Desktop 123:07:07> --- virtual Desktop 223:07:09> --- virtual Desktop 312:59:04> --- virtual Desktop 113:41:53> --- virtual Desktop 513:47:09> --- virtual Desktop 3'''# split on lines, remove empty lines and get only hour and dekstop number
lines = text.split('\n')
lines = [x.strip().split('> --- virtual Desktop ') for x in lines if x.strip()]#print(lines)desktop = dict() # for total time for every desktop
diff_24h = datetime.timedelta(days=1) # for some calculations# works with pairs of lines
for previous, current in zip(lines, lines[1:]):prev_hour, prev_desktop = previouscurr_hour, curr_desktop = currentprint('desktop', prev_desktop, 'start', prev_hour, 'end', curr_hour)# covnert to datetimeprev_dt = datetime.datetime.strptime(prev_hour, '%H:%M:%S')curr_dt = datetime.datetime.strptime(curr_hour, '%H:%M:%S')# calculate different between hours - if current < prev then there is new day and it need correction diff_24hif curr_dt < prev_dt:diff_dt = (curr_dt - prev_dt) + diff_24helse:diff_dt = (curr_dt - prev_dt)print('desktop', prev_desktop, 'running', diff_dt)print('---')# add time to dictionary to get total timeif prev_desktop not in desktop:desktop[prev_desktop] = datetime.timedelta()desktop[prev_desktop] += diff_dtprint('--- results ---')    
for key, value in desktop.items():print('desktop', key, 'total time', value)

Result:

[['09:43:04', '2'], ['12:37:20', '6'], ['23:07:00', '1'], ['23:07:07', '2'], ['23:07:09', '3'], ['12:59:04', '1'], ['13:41:53', '5'], ['13:47:09', '3']]
desktop 2 start 09:43:04 end 12:37:20
desktop 2 running 2:54:16
---
desktop 6 start 12:37:20 end 23:07:00
desktop 6 running 10:29:40
---
desktop 1 start 23:07:00 end 23:07:07
desktop 1 running 0:00:07
---
desktop 2 start 23:07:07 end 23:07:09
desktop 2 running 0:00:02
---
desktop 3 start 23:07:09 end 12:59:04
desktop 3 running 13:51:55
---
desktop 1 start 12:59:04 end 13:41:53
desktop 1 running 0:42:49
---
desktop 5 start 13:41:53 end 13:47:09
desktop 5 running 0:05:16
---
--- results ---
desktop 2 total time 2:54:18
desktop 6 total time 10:29:40
desktop 1 total time 0:42:56
desktop 3 total time 13:51:55
desktop 5 total time 0:05:16
https://en.xdnf.cn/q/118660.html

Related Q&A

Error installing eomaps through conda and pip

I am getting the following error output when trying to install eomaps using Conda. I dont know how to solve this. I have also tried the same using pip but it didnt seem to solve the problem. Here is th…

DFS on a graph using a python generator

I am using a generator to do a full search on a graph, the real data set is fairly large, here is a portion of the code i wrote on a small data set:class dfs:def __init__(self):self.start_nodes = [1,2]…

Importing test libraries failed. No module named a

I have a folder /example which contains /Libs which further contains different folders /a, /b each containing python libraries. I am trying to run a robot framework code from /example.The error it show…

Sorting characters by count using PHP or Python

I have a string of charactersabcdefghijklmnopqrstuvwxyz_ I want to take this string of characters and sort them by the number of times they appear in a large block of characters. For example: cwrxwzb…

Save user first_name as default value for model django

I have an article model with author variable which I want to save as the users first and last name. I use custom user model called Account. author = models.CharField(author,max_length=50 default=User.f…

How to compare two imagefile from two different files in python

I would like to create a program that compares two images. I need to take images from two different folders and compare that images if they are same or not. Then I want to print out as same or differen…

Cant import from module despite presence of __init__.py

I have the following folder structureproject_folder/pyutils/__init__.pyscript1.pyscript2.py lambdas/__init__.pylambda_script1.pylambda_script2.pylambda_tests/__init__.pylambda_test1.pyWithin lambda_tes…

Multiple strings in one variable

Say, for example, I have some code that goes like this: sentence = input("Enter input: ") target_letter = "a" or "b" or "c" print(sentence.index(target_letter))M…

How to get the area of shape filled using turtle

I graphed a fractal shape in Python using turtle, and am trying to get the area of this fractal after a sufficiently high iteration. This fractal is related to the Koch snowflake, for those interested.…

What distinguishes a command from needing () vs not?

I recently spent way too long debugging a piece of code, only to realize that the issue was I did not include a () after a command. What is the logic behind which commands require a () and which do not…