Python 在按顺序读取文本文件时,如何返回到特定行并从该行重新开始
新手警报Python 在按顺序读取文本文件时,如何返回到特定行并从该行重新开始,python,Python,新手警报 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("lin
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中再次从该行开始读取。当我尝试在代码的最后但第5行中使用f.readlines()时,处理就在那里停止。。。。上面的代码。。。
... code above ...
for line in data:
if counter_end<= <line to stop at>:
continue
counter_end += 1
...
对于行输入数据:
如果counter_enda=linecache.getlines('D:/aaa.txt')[5]您可以建立一个行起始位置(文件偏移量)列表,然后使用file.seek(行偏移量[n])
返回到n
th行(从零开始计数)。之后,您可以再次阅读该行(以及随后的内容)
下面的示例代码显示以增量方式构建这样的列表:
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 """
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 """