I'm doing an exercise that takes in a file with data of server room temperatures and I want to print out all of the average temperatures of all the years. So I need to get the next line in the file to determine what the next year is. I tried next() but that forces the for loop to go to the next iteration. I need the 1st and 2nd line then move to the 2nd line and get the 3rd line, etc.
Here is the portion of code:
with open("THUMlog.txt", "r") as file:
for line in file:
if line == "#DATE TIME TEMPERATURE UNIT HUMIDITY%\n":
continue
stripped_line = line.rstrip().split()
next_line = next(file, "").rstrip().split()
print(f"Stripped: {stripped_line}")
print(f"Next: {next_line}")
Portion of Output (Very large file):
Stripped: ['9/28/2010', '15:45:14', '22.248900', 'C', '44.721968']
Next: ['9/28/2010', '16:00:07', '22.738900', 'C', '50.539993']
Stripped: ['9/28/2010', '16:15:07', '23.388900', 'C', '49.339338']
Next: ['9/28/2010', '16:30:07', '23.918900', 'C', '47.539280']
Stripped: ['9/28/2010', '16:45:08', '23.668900', 'C', '40.700378']
Next: ['9/28/2010', '17:00:07', '23.438900', 'C', '40.130996']
Stripped: ['9/28/2010', '17:15:07', '23.188900', 'C', '40.546257']
Next: ['9/28/2010', '17:30:07', '23.038900', 'C', '40.361183']
Stripped: ['9/28/2010', '17:45:07', '22.978900', 'C', '40.356943']
Next: ['9/28/2010', '18:00:08', '22.808900', 'C', '40.239134']
Stripped: ['9/28/2010', '18:15:07', '22.748900', 'C', '40.329383']
Next: ['9/28/2010', '18:30:07', '22.588900', 'C', '40.347069']
So basically, The first Next should be the same list as the second Stripped. I tried concatenating all these lists into a list so I could easily get the next one through indexing but I get time limit exceeded probably because I had 2 for loops, one looping through the entire file, splitting the line into a list, and appending to another list. Then another looping through the list of list. This effectively doubles the amount of time. This is a bonus exercise in my programming course and is done in software that runs and checks your solution.
with open("file.txt") as f: content = f.readlines()