1

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

Jeez123
  • 9
  • 5

2 Answers2

0

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))
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • `with open("username.txt") as f: print(f.readlines()) print([line.rstrip('\n') for line in f.readlines()].index('jeez123'))` – Jeez123 Jul 22 '20 at 11:58
  • `Traceback (most recent call last): File "C:/Users/Admin/PycharmProjects/log in and out/testing file.py", line 3, in print([line.rstrip('\n') for line in f.readlines()].index('jeez123')) ValueError: 'jeez123' is not in list ['\n', 'nono\n', 'jeez123\n']` – Jeez123 Jul 22 '20 at 11:58
  • sorry for the messy comment i'm new to coding and also new to overflow. sorry for any confusion. – Jeez123 Jul 22 '20 at 11:59
  • You should remove `print(f.readlines())` since it reads the file content and moves the file pointer to the end of the file so that the next cannot read the content anymore. – blhsing Jul 22 '20 at 12:16
  • See demo: https://repl.it/@blhsing/FuzzyWhimsicalEfficiency#main.py – blhsing Jul 22 '20 at 12:20
0

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
irudyak
  • 2,271
  • 25
  • 20