简体   繁体   中英

Python "for line in file", read the next n lines

I am trying to create a few graphs from a text file, each depending of the flow rate of the test saved in the file (50000000bps, 100000000bps, ...).

A part of the file :

Test n4721 : 100000000bps
 > ping request = 756811
 > ping reply = 338566
 > Loss = 55.26412803196571%

Loss from start : 89.43101573304583%
- - - - - - - - - - - - - - - - - - - - - -


Test n4722 : 50000000bps
 > ping request = 378405
 > ping reply = 195513
 > Loss = 48.33234233162881%

Loss from start : 89.42231207497692%
- - - - - - - - - - - - - - - - - - - - - -

I am opening the file with file = open("result.txt","r") and going through it with for line in file: .

When an if loop coresponding to a flow rate match a line (ie "50000000bps"), I need to append to an array the value of the next lines : Loss and Loss from start .

This is how my code is going from now :

file = open("result.txt","r")

for line in file:
    count += 1

    if "50000000" in line:
        current_loss = line(count + 3) # Don't work, like : line[count + 3] file[count + 3]
        print(current_loss)

        start_loss = line(count + 5) # Don't work, like : line[count + 5] file[count + 5]
        print(start_loss)

Do you know how can I read the next n line from the one I am curently reading ?

Call readline() every time you want to read another line from your input file. For your given logic, then, that might look like:

infile = open("result.txt","r")

for line in infile:
    if "50000000bps" in line:
        _, _, loss = infile.readline(), infile.readline(), infile.readline()
        _, loss_from_start = infile.readline(), infile.readline()
        print(loss.rstrip())
        print(loss_from_start.rstrip())

See this running athttps://replit.com/@CharlesDuffy2/RoughTreasuredFolders#main.py

If you want to loop inside your file lines, you can use:

file = open("result.txt","r")
file_lines = file.readlines()

for line in file_lines:

#rest of your code

To get your Kth line from your lines:

file = open("result.txt","r")
file_lines = file.readlines()

for k in range(len(file_lines)):
     kth_line = file_lines[k]
  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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