In article <11**********************@g44g2000cwa.googlegroups .com>,
ne*****@xit.net wrote:
hey there,
i need to be able to get the index for an item in a list.
the list is a list of lines read from a text file.
like this:
file = open("/home/somefile.text", "r")
lines = file.readlines()
file.close()
now, i want to see if a certain string is == to one of the lines
and if so, i need to know the index of that line.
Assuming you're already read the lines from the file with the above code,
something along the lines of the following will work:
for lineNumber, line in enumerate (lines):
whatever
But, starting from scratch, it'll be more efficient to do:
for lineNumber, line in enumerate (file ("filename")):
whatever
because it'll read lines one at a time as needed, instead of gulping them
all in at once and buffering them in memory. For small files (say, less
than a few hundred lines), it probably won't make any appreciable
difference, but for big files, it can be substantial.
BTW, enumerate() starts counting from 0; you might want to add 1 to what it
returns to get a file line number.