Jul-09-2020, 09:14 AM
Hello, I'm new to the forum so hello all! I've looked for the solution to my problem in the forum, but I didn't find it, so I ask. I apologize if this was already discussed and I've missed it. The problem I'm facing is the following. I have a file which looks like this
Line 1
34
Line 2
78
Line 3
88
and what I want to do is to read the file and when the string Line 1 and Line 3 are found, save the values 34 and 88. Unfortunately this file is generate by an external code, so I cannot modify this structure.
I wrote a code that works, but what I'm doing is looping twice on the file. I'm doing it in the following way. Firstly I find the line number where my string is, then in the second loop I save the string of the line number. Clearly this is inefficient for large files. Is there a way to do this in one single loop?
Thanks for the help
Daniele
Line 1
34
Line 2
78
Line 3
88
and what I want to do is to read the file and when the string Line 1 and Line 3 are found, save the values 34 and 88. Unfortunately this file is generate by an external code, so I cannot modify this structure.
I wrote a code that works, but what I'm doing is looping twice on the file. I'm doing it in the following way. Firstly I find the line number where my string is, then in the second loop I save the string of the line number. Clearly this is inefficient for large files. Is there a way to do this in one single loop?
Thanks for the help
Daniele
file = open(file.txt","r") for line_no, line in enumerate(file): if "Line 1" in line: position = line_no+1 file.close() ## file = open(file.txt","r") for line_no, line in enumerate(file): if line_no == position: results = float(line.split()[0]) file.close()