Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with text file in Python

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

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

I would like to skip to the line in the file after a particular string "charts" which occurs at around line no. 7000 (different for different files). Is there a way to conveniently do that without having to read each single line of the file?

like image 848
DPdl Avatar asked Mar 07 '23 16:03

DPdl


1 Answers

If you know the precise line number then you can use python's linecache module to read a particular line. You don't need to open the file.

import linecache

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

Output:

chart

If you want to start reading from that 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)

Output:

chart
dang!
It
Works

If you don't know the precise line number and want to start after the line containing that particular string, use another for 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) 

Output:

dang!
It    
Works

test.txt contains:

hello
world!
chart
dang!
It
Works

I don't think you can directly skip to a particular line number. If you want to do that, then certainly you must have gone through the file and stored the lines in some format or the other. In any case, you need to traverse atleast once through the file.

like image 72
Miraj50 Avatar answered Mar 21 '23 02:03

Miraj50