Use readline () from python to read a specific line

When using readline () in python, you can specify which line to read? When I run the following code, I get lines 1,2,3, but I would like to read lines 2,6,10

def print_a_line(line, f):
    print f.readline(line)

current_file = open("file.txt")

for i in range(1, 12):
    if(i%4==2):
        print_a_line(i, current_file)
+4
source share
4 answers
with open('file.txt', 'r') as f:
    next(f)
    for line in f:
        print(line.rstrip('\n'))
        for skip in range(3):
            try:
                next(f)
            except StopIteration:
                break

File:

1
2
3
4
5
6
7
8
9
10

Result:

2
6
10

This will work for a script or function, but if you want it to hide missing lines in an interactive shell, you need to save the calls next(f)to a temporary variable.

+2
source

, readline . , . , , ( ). , , , , .

with open('my_file') as f:
    for i, line in enumerate(f, start=1):
        if i > 12:
            break
        if i % 4 == 0:
            print(i, line)

, , , .

line_len = 20  # bytes

with open('my_file', 'rb') as f:
    for i in range(0, 13, 4):
        f.seek(i * line_len)
        print(f.read(line_len).decode())
+3

itertools, :

from itertools import islice
from collections import deque

def consume(iterator, n):
    "Advance the iterator n-steps ahead. If n is none, consume entirely."
    # Use functions that consume iterators at C speed.
    if n is None:
        # feed the entire iterator into a zero-length deque
        deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(islice(iterator, n, n), None)

with open("in.txt") as f:
    l = []
    sm = 0
    for i in (2, 6, 10):
        i -= sm
        consume(f, i-1)
        l.append(next(f, ""))
        sm += i

, , , i. :

def get_lines(fle,*args):
    with open(fle) as f:
        l, consumed = [], 0
        for i in args:
            i -= consumed
            consume(f, i-1)
            yield next(f, "")
            consumed += i

:

test.txt:

1
2
3
4
5
6
7
8
9
10
11
12

:

In [4]: list(get_lines("test.txt",2, 6, 10))
Out[4]: ['2\n', '6\n', '10\n']
In [5]: list(get_lines("stderr.txt",3, 5, 12))
Out[5]: ['3\n', '5\n', '12']

, linecache:

import linecache

linecache.getline("test.txt",10)
+3
source

A file is always read from the first character. The reader does not know the content, therefore, does not know where the lines begin and end. readlinejust reads until it sees a newline character. This is true for any language, not just Python. If you want to get the nth line, you can skip the n-1 line:

def my_readline(file_path, n):
    with open(file_path, "r") as file_handle:
        for _ in range(1, n):
            file_handle.readline()
        return file_handle.readline()

Remember that with this solution you need to open a file with every function call, which can seriously reduce the performance of your program.

+1
source

All Articles