Working with a text file in Python

I am reading a text file with a number> 10,000 lines.

results_file = open("Region_11_1_micron_o", 'r')

I would like to go to the line in the file after the specific line of the “chart” that appears around line No. 7000 (different for different files). Is there a way to do this without having to read every single line of the file?

+4
source share
3 answers

If you know the exact line number, you can use the python module to read a specific line. You do not need to open the file. linecache

import linecache

line = linecache.getline("test.txt", 3)
print(line)

Conclusion:

chart

If you want to start reading from this line, you can use . islice

from itertools import islice

with open('test.txt','r') as f:
    for line in islice(f, 3, None):
        print(line)

Conclusion:

chart
dang!
It
Works

If you do not know the exact line number and want to start after the line containing this particular line, use another for the loop.

with open('test.txt','r') as f:
    for line in f:
        if "chart" in line:
            for line in f:
                # Do your job
                print(line) 

Conclusion:

dang!
It    
Works

test.txt contains:

hello
world!
chart
dang!
It
Works

, . , , , . .

+5

itertools.dropwhile, .

from itertools import dropwhile, islice

with open(fname) as fin:
    start_at = dropwhile(lambda L: 'Abstract' not in L.split(), fin)
    for line in islice(start_at, 1, None):
        print line
+1

If your text file has lines whose length is evenly distributed across your file, you can try to find in the file

from os import stat
size = stat(your_file).st_size
start = int(0.65*size)
f = open(your_file)
f.seek(start)
buff = f.read() 
n = buff.index('\nchart\n')
start = n+len('\nchart\n')
buff = buff[start:]
+1
source

Source: https://habr.com/ru/post/1688825/


All Articles