繁体   English   中英

在顺序阅读文本文件时,如何返回到特定行并从那里重新开始

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

新手警报!

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

我想知道如何返回文件中的特定行,然后从python中再次开始读取。 当我尝试在代码的最后但第五行中使用f.readlines()时,处理就在那里停止。

您可以建立行起始位置(文件偏移)列表,然后使用file.seek(line_offsets[n])返回第n行(从零开始计数)。 之后,您可以再次读取该行(以及依次跟踪的行)。

以下示例代码显示了逐步构建这样的列表:

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 """
... code above ...
for line in data:

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

    counter_end += 1

...

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM