-1

I have a file that contains a list of names, one name per line.

I want to check if a name already exists in the file. If it doesn't, I want to append it at the end of the file.

names.txt

Ben
Junha
Nigel

Here is what I tried to do:

    name=raw_input(" Name: ")
    with open("names.txt") as fhand:
        if name in fhand:
            print "The name has already been in there"
        else:
            with open("file.txt","a+") as fhand:
                fhand.write(name)

but the existing names are never found, and the names I enter always get appended to the last line.

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
An Bùi
  • 11
  • 2
  • It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ] and [ask] – Skam Jul 15 '17 at 05:07
  • Possible duplicate of https://stackoverflow.com/questions/4940032/search-for-string-in-txt-file-python. – Arya McCarthy Jul 15 '17 at 06:01

1 Answers1

1

Your general idea is good, but a few details are off.

Rather than opening the file twice, once in read mode and then in append mode, you can open it once in read/write(r+) mode.

open() returns a file object, not text. So you can't just use if some_text in open(f). You must read the file.
As your data is structured line by line, the easiest solution is to use a for loop that will iterate on the lines of the file.

You can't use if name in line, because "Ben" in "Benjamin" would be True. You must check that names really are equal.

So, you could use:

name=raw_input(" Name: ")
# With Python 3, use input instead of raw_input

with open('names.txt', 'r+') as f:
    # f is a file object, not text.
    # The for loop iterates on its lines
    for line in f:
        # the line ends with a newline (\n),
        # we must strip it before comparing
        if name == line.strip():
            print("The name is already in the file")
            # we exit the for loop
            break
    else:
    # if the for loop was exhausted, i.e. we reached the end, 
    # not exiting with a break, this else clause will execute.
    # We are at the end of the file, so we can write the new 
    # name (followed by a newline) right where we are.
        f.write(name + '\n')
Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50