-2

I want to know if there is a way to find the line number of a line in a text file, using Python.

So, for example, if we have the file textfile.txt:

abc
deff
ghi
jkl
EOF

Then I'd like a function like func(FILE,TEXT), that would work in the following way:

Input:  func(textfile.txt, "ghi")
Output: 3
Joe Iddon
  • 20,101
  • 7
  • 33
  • 54

4 Answers4

1

You can do this in one line with next() called on a generator that uses the enumerate() function to get the index of the line.

So, as a function:

def func(f, t):
    return next(i for i, l in enumerate(open(f).read().split('\n'), 1) if l == t)

which would be called through something like:

func('textfile.txt', 'ghi') # --> 3

note: the enumerate(..., 1) trick was from @KeyurPotdar, so creds

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
0
file_name="test.txt"
phrase="line3"
with open(file_name) as f:
    for i, line in enumerate(f, 1):
        if phrase in line:
           print(i)
Joao
  • 37
  • 9
0

Maybe that's waht you're looking for:

def fn(fname, substr):
    with open(fname) as text:
        for n, line in enumerate(text, start=1):
            if line.startswith(substr):
                return n
    return -1

Don't be afraid to study the python docs on string functions, file I/O, context managers etc. You'll be shocked on how easy things like this are to accomplish.

Gomes J. A.
  • 1,235
  • 2
  • 9
  • 9
0

This might help.

def LineNumber(phrase,textObjext):
    for i, line in enumerate(textObjext, 1):
        if phrase in line:
           return i

file_name="test.txt"
phrase="deff"
text = open(file_name,'r')
line = LineNumber(phrase,text)
print(line)
Hayat
  • 1,539
  • 4
  • 18
  • 32