n004rp
n004rp

Reputation: 45

How to check if an element is not in file?

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

Upvotes: 0

Views: 185

Answers (1)

Frank
Frank

Reputation: 2029

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

Upvotes: 3

Related Questions