Unable to loop over a file using context manager python3
Solution 1:
It appears that you are using readlines()
instead of .readline()
on the time_check line.
import time
instances = ['XYZ']
curr_date = time.strftime("%Y%m%d")
for inst_name in instances:
with open(f'results_{inst_name}_master.csv') as f:
pkt_name = f.readline().split(';')[1]
print(f"package name is: {pkt_name}")
run_dt = f.readline().split(';')[1]
This line appears to be incorrect. It calls readlines
and references the element at the first index. I removed the s
and the index reference.
time_check = f.readline().split(';')[-5].split(':')[0]
print(f"time is : {time_check}")
if ((run_dt == curr_date) or (run_dt < curr_date and time_check in range(20,24))):
for index, l in enumerate(f, 1):
if 'remoteInstallation' in l:
print(l)
What happened behind the scenes?
For file objects (in this case f
) there is an internal pointer that keeps track of where in the file the script is currently looking. This pointer is universal and used by multiple functions and by for loops.
Each call to readline()
will read a line from the file and move the pointer to the next line.
Any call to readlines()
will read all the lines until the end of the file and move the pointer to the end of the file.
For loops read the next line (if there is one) and keep repeating that process until the pointer is at the end of the file. In our code, this line:
for index, l in enumerate(f, 1):
is a for loop that is attempting to read more lines from the file.
Unfortunately, in our case, by calling readlines()
, we have already read all the lines from file and have already moved the pointer to the end of the file and thus the for loop was unable to read in any new lines.