Kailash Mallikarjun
Kailash Mallikarjun

Reputation: 13

While reading a text file sequentially how to go back to a particular line and start again from there

Newbie alert!

Path = "C:/Users/Kailash/Downloads/Results_For_Stride-Table.csv"
counter_start = 0
counter_end = 0
num_lines = len(open(Path).read().splitlines())
print("num_lines = ", num_lines)
with open(Path, "r") as f:
    for lines in f:
        print("lines = ", lines)
        counter_end += 1
        Stride_Length = lines.split(", ")
        Previous_Sum = distances
        Previous_Sum_GCT = Total_GCT
        Previous_Heading = Sum_Heading
        GCT = float(Stride_Length[2])
        Total_GCT += GCT
        print("Total_GCT = ", Total_GCT)
        distances += float(Stride_Length[3])
        print("distances = ", distances)
        Sum_Heading += float(Stride_Length[7])
        print("Sum_Heading = ", Sum_Heading)
        print("counter_end = ", counter_end)
        if(GCT == 0.00):
            distances = 0
            counter_end = 0            
        if distances > 762:
           print("counter_end = ", counter_end)
           counter_start = counter_end
           lines_test = f.readlines()
           print("counter start = ", counter_start)
           print("move = ", lines_test[counter_start-counter_end-1])
           print("Distance is above 762")
           distances = 0

I want to know how to go back to a particular line in a file and start reading from there again in python. when I try to use f.readlines() in the last but 5th line in my code, the processing stops right there.

Upvotes: 0

Views: 114

Answers (4)

pyy
pyy

Reputation: 31

import linecache
a = linecache.getlines('D:/aaa.txt')[5]

Upvotes: 0

martineau
martineau

Reputation: 123393

You can build a list of line start positions (file offsets), and then use file.seek(line_offsets[n]) to go back to the nth line (counting from zero). After that you can read the line (and those following it sequentially) once again.

Here's example code showing building such a list incrementally:

filepath = "somefile"
line_offsets = []

with open(filepath, "r") as file:
    while True:
        posn = file.tell()
        line = file.readline()
        if not line:  # end-of-file?
            break
        line_offsets.append(posn)  # Remember where line started.
        """ Process line """

Upvotes: 1

pyy
pyy

Reputation: 31

a = linecache.getlines('D:/aaa.txt')[5]

Upvotes: 0

Ryan JB
Ryan JB

Reputation: 1

... code above ...
for line in data:

    if counter_end<= <line to stop at>:
        continue

    counter_end += 1

...

Upvotes: 0

Related Questions