I’m new to python (and in any real sense) to programming. I’ve been playing around with this problem and here’s my extended solution to repeatedly check a whitelist file to see whether user input domains are whitelisted (one at a time). The whitelist file contains a list of domains (one per record).
It appears to work but I got there by trial and error. Can this be done in a more elegant, efficient and ‘pythonic’ manner? I’ve not got round to error checking yet (if that is relevant). Any tips gratefully received.
#!/usr/bin/env python3
# Filename: whitelist.py
domain = 1
match = 0
while domain:
domain = input('Enter a domain or press return to exit: ')
if not domain: # if return is pressed entered then end program
break
with open('whitelist.txt', 'r', encoding='utf-8') as whitelist:
for recd in whitelist:
# if input domain doesn't match record read next record (continue)
if recd.lower().rstrip() != domain.lower():
continue
else: # otherwise if match set match indicator
match = 1
break # after setting indicator stop reading records
if match:
print('Match on domain: ', domain)
else:
print('No match on: ', domain)
After taking on board larsmans’ comments my new solution is basically his solution with a slight change to make all checks use lower case (e.g. so cnn.com == CNN.com):
#!/usr/bin/env python3
# Filename: whitelist.py
with open('whitelist.txt', 'r', encoding='utf-8') as f:
whitelist = set(line.lower().rstrip() for line in f)
while True:
domain = input('Enter a domain or press return to exit: ')
if not domain:
break
if domain.lower() in whitelist:
print('Match on domain: ', domain)
else:
print('No match on: ', domain)
can be written more succintly
Also, you should be using
TrueandFalsefor booleans, rather than 0 and 1.Third, you should really be reading the whitelist file once, outside of the loop. Ideally, you’d read it into a
setto allow for fast lookup.Then the loop becomes
Note that I’ve changed the loop condition to
while Truebecause the check fornot domainalready occurs inside it.