0

I didnt know how to word the title, but here's the code:

file = open('blah.txt', 'r')
line = file.read()
file.close()
stuff = input('enter stuff here')
if stuff in line:
   print('its in the file')
else:
   print('its not in the file')

and here's blah.txt:

text,textagain,textbleh

If the user input is found in the file, is there a way to also output the position of the string entered by the user? For example, if the user entered 'textagain', is there a way to output '2' because the string 'textagain' is in the second position in the file?

Thank you in advance.

petezurich
  • 9,280
  • 9
  • 43
  • 57
someguy
  • 21
  • 2
  • "if the user entered 'textagain', is there a way to output '2' because the string 'textagain' is in the second position in the file?" I don't think it makes sense to say that it is in such a position, and I don't understand what your reasoning is. But none of this has anything to do with files; once you've read the contents of the file into a string, you work with the string the same way you would work with any other string. – Karl Knechtel Mar 19 '21 at 10:41

2 Answers2

2

What @Amiga500 said would likely work with some wrangling, I suggest splitting your strings up.

"text,textagain,textbleh".split(",") would return ['text', 'textagain', 'textbleh'] at which point you can do .index(your_word) and get back the index (1 for textagain since Python uses zero based indexing and it is the second entry).

So the final code might be:

file = open('blah.txt', 'r')
line = file.read()
file.close()
stuff = input('enter stuff here')
if stuff in line.split(","):
   print('its in the file')
else:
   print('its not in the file')
Alexis Drakopoulos
  • 1,115
  • 7
  • 22
0

Try this:

line.index(stuff)

i.e.

if stuff in line:
     posit = line.index(stuff)

If you try jumping straight to the index and its not there, it'll throw an error. You could use a try except as a workaround, but its ugly.

Ah, sorry, misread. You've a csv file.

Use the csv reader in python to read it in:

Python import csv to list

Then loop through (assuming line is the sub-list for each line):

if stuff in line:
    posit = line.index(stuff)
Amiga500
  • 1,258
  • 1
  • 6
  • 11