0

How to check if an element is not in a python File, I tried:

if not element in File.read()

But the "not in" doesn't seems to work I also tried:

if element not in File.read()

Edit: Code Snippet

phone = input('Enter a new number :')
imp = phone

if phone not in phbook.read() and phone_rule.match(imp):
    phbook = open('Phonebook','a')
    phbook.write('Name: ' + firstname + '\n')
    phbook.write('Phone: ' + phone + '\n')

if phone in phbook.read():
    print('sorry the user already have this phonenumber ')
else:
    if phone_rule.match(imp):
        phbook = open('Phonebook','a')
        phbook.write('Name: ' + firstname + '\n')
        phbook.write('phone: ' + phone + '\n')
        print('user added !')
    else:
        print('This is not a good format')

Not working either

martineau
  • 119,623
  • 25
  • 170
  • 301
n004rp
  • 45
  • 5
  • 1
    You did not share the entirety of your code, but it looks like you are trying to read from a file object multiple times. However, after the first `.read()`, additional reads will just return an empty string because the cursor is at the end of the stream already. Although your issue is about the first `.read()` in your snippet, if you have other reads above that one, it could be causing your issue. – James Jan 11 '22 at 19:19

1 Answers1

3

You need to open the file before accessing it.

After reading it, the file cursor is at the end of the file. You could use phbook.seek(0) to set the cursor at the beginning of the file.

A cleaner way would be to ensure you are using your file only once giving it a better structure, eg:

phone = input('Enter a new number :')
imp = phone
phonebook_filename = 'phonebook.txt'

def ensure_phone_in_phonebook(phone):
    with open(phonebook_filename) as phbook:
        if phone not in phbook.read() and phone_rule.match(imp):
            add_data(firstname, phone)

def add_data(firstname, phone):
    with open(phonebook_filename, 'a') as phbook:
        phbook.write('Name: ' + firstname + '\n')
        phbook.write('Phone: ' + phone + '\n')

ensure_phone_in_phonebook(phone)

Also note the usage of context manager statement with.

It bewares you of closing the file after using.

Further informations

Jasmijn
  • 9,370
  • 2
  • 29
  • 43
Frank
  • 1,959
  • 12
  • 27