is it possible to find the position of a word in a text file?
The text file looks like this
Cat
Dog
Wolf
i tried using
print(file.readlines.index("word"))
but sadly it doesn't work
is it possible to find the position of a word in a text file?
The text file looks like this
Cat
Dog
Wolf
i tried using
print(file.readlines.index("word"))
but sadly it doesn't work
The strings in the list returned by the readlines
method each end with a newline character, so you should strip the strings of the trailing newlines before matching them with the index
method:
print([line.rstrip('\n') for line in file.readlines()].index('word'))
Since all you're looking for is the index of the first matching word, you can also improve the time and memory efficiency by using a generator expression instead:
print(next(i for i, line in enumerate(file) if line.rstrip('\n') == word))
The issue here that readlines()
reads new line symbol \n
- see here.
Here's an example:
In [12]: cat animals.txt
Cat
Dog
Wolf
In [13]: with open('animals.txt') as f:
...: print(f.readlines())
...:
['Cat\n', 'Dog\n', 'Wolf\n']
In [14]: with open('animals.txt') as f:
...: print(f.read().splitlines())
...:
['Cat', 'Dog', 'Wolf']
In [15]: with open('animals.txt') as f:
...: print(f.read().splitlines().index('Dog'))
...:
1