1

I need to get a specific line number from a file that I am passing into a python program I wrote. I know that the line I want will be line 5, so is there a way I can just grab line 5, and not have to iterate through the file?

1
  • 1
    Unless you know the specific buffer position of line 5, you must iterate through lines 1-4 to reach line 5. This is because lines are determined by the presence of newlines \n within the file. Is this what you are asking? Or do you mean, that you don't want to load the entire file in order to retrieve line 5? Commented Mar 4, 2012 at 13:27

3 Answers 3

3

If you know how many bytes you have before the line you're interested in, you could seek to that point and read out a line. Otherwise, a "line" is not a first class construct (it's just a list of characters terminated by a character you're assigning a special meaning to - a newline). To find these newlines, you have to read the file in.

Practically speaking, you could use the readline method to read off 5 lines and then read your line.

Why are you trying to do this?

Sign up to request clarification or add additional context in comments.

3 Comments

some project I need to do for my AI class. Basically, I'm being passed a text file, and I know that the line 5 contains the number of blocks for my solver. It is essentially a program that converts a text file to a SAT instance.
That's fine. Why do you need to skip lines till the 5th. What's wrong with reading and discarding them?
I could do that.. I just need to be able to get whatever is on the 5th line.
3

you can to use linecache

import linecache
get = linecache.getline
print(get(path_of_file, number_of_line))

2 Comments

Nice. I didn't know about the module. Although I'm not sure it solves the problem here.
see my example and see the documentation ;)
0

I think following should do :

line_number=4

# Avoid reading the whole file
f = open('path/to/my/file','r')
count=1
for i in f.readline():
    if count==line_number:
        print i
        break
    count+=1

# By reading the whole file
f = open('path/to/my/file','r')
lines = f.read().splitlines()
print lines[line_number-1]     # Index starts from 0

This should give you the 4th line in the file.

4 Comments

this looks like it would work, but I need to grab the file passed in from the command line... so something like python myprogram blocks.txt and I need to grab the 5th line from blocks.txt
The only problem with this solution is that it would read the entire file into memory.
Fixed.. by adding the other waay.
In the first case, you are reading the first 4 lines (although not using them) using readline (also, you can say for i in f). In the second case, you're reading the entire file into memory and then "parsing" it for newlines which is probably not a good idea.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.