Ask coding questions

← Back to all posts
Searching string from text file in Python
FatimaNadeem1 (0)

Hi everyone!
I'm trying to create a program in Python where a user enters a name they would like to search from a text file and the program either answers "Name found" or "Name not found".
I tried using all of the knowledge I have but cannot do it because even if you type the first letter of a name, the program says "Name found" which shouldn't happen.
Thanks

Answered by MrVoo (102) [earned 5 cycles]
View Answer
Comments
hotnewtop
MrVoo (102)

Try adding a ; to the beginning and end of every name in the file (like ;Bob;) and do this:

name = input('Name: ')
name = ';'+name+';'
if name in file:
  print('yeehaw')
FatimaNadeem1 (0)

@MrVoo
it says:
Traceback (most recent call last):
File "main.py", line 12, in <module>
if name in file:
ValueError: I/O operation on closed file.

MrVoo (102)

@FatimaNadeem1 The repl isn't changed, did you try it on another one?

MrVoo (102)

Also you spelled "John" wrong

MrVoo (102)

@FatimaNadeem1 Try file.read() instead of file

FatimaNadeem1 (0)

@MrVoo All of the changes are done on this repl, I'm not sure why you can't see.
I'm assuming the mistake is on Line 10 where it says:

  • if name in file:
    because the error on the console says:
    "io.UnsupportedOperation: not readable"
FatimaNadeem1 (0)

@MrVoo It still come as an error :(

FatimaNadeem1 (0)

@MrVoo Lol, that's not really important, is it? Oh well, ty for letting me know.

MrVoo (102)

@FatimaNadeem1 You forgot to close and reopen the file, add that on line 7

FatimaNadeem1 (0)

@MrVoo Yep, noticed that too. The file was open on write mode so I had to close and reopen on read mode.
Thank you so much for your help c:

MrVoo (102)

@FatimaNadeem1 One more thing, you don't have to write the file every time. Mark as correct? :3

FatimaNadeem1 (0)

@MrVoo What's an easier way then without having to write file?
btw done :3

MrVoo (102)

@FatimaNadeem1 All you have to do is type in the file, and since it's your repl it'll save.