Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

readline() and specifying line number

Status
Not open for further replies.

dbrb2

Instructor
Jul 19, 2004
121
0
0
GB
A very basic question... I'm new to Python...

Using repeated calls to:

line=input.readline()

I can read succesive lines from a text file. Since each time I call this function I get the next line, there must be a poiter somewhere being incremented. Is there a way to manipulate this pointer such that I can instead specify the line I want to read (say line 5 or line 10) Of course I could just run the above x times to capture line x, but that seems very wasteful...

Cheers,

Ben
 
Have you tried reading in the entire file? Not practical for massive files I know...

f = file('filename', 'r').readlines()
print f[linenumber]

you can also iterate over the file line by line:

for l in f:
print l

May use lots of memory if you have a BIG file - but it sure is quick.
 
There is a Seek Method but it is Byte based not line based. If your file has lines of a known/constant byte length, this will work.

The problem with something to move to a specific line is that the program has know way to know how many bytes to skip over to get to the line you want. The only way to know this is to read the file into a buffer until it gets to the line you are looking for. This is exactly the same thing that you do with your repeated calls to Readline().

[red]"... isn't sanity really just a one trick pony anyway?! I mean, all you get is one trick, rational thinking, but when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick[/red]
 
The only way to know this is to read the file into a buffer until it gets to the line you are looking for"

Good point. So I could puttogether a simple function to read a specified line, but it would do it by reading in every preceeding line and counting them as it went.

Cheers,

Ben
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top