Reputation: 75
I use https://github.com/daviddrysdale/python-phonenumbers in my project to fix all bad numbers.
import csv
import phonenumbers
with open('base.csv') as f:
data = list(csv.reader(f, delimiter=';'))
header_row = data[0]
header_row[8] = "Fixed Home Phone"
header_row[13] = "Fixed Mobile Phone"
for row in data[1:6]: # we go from first because there is header row
try:
print(f'Original row - {row[7]}')
x = phonenumbers.parse(row[7], "RU") #LOOK HERE! sometimes exception, due to blank field
print(x)
num2 = phonenumbers.parse(row[12], "RU")
print(f'Phone Num Script Response - {num2}') # sometimes exception is here
print("To national format - ", phonenumbers.format_number(x, phonenumbers.PhoneNumberFormat.E164))
row[8] = phonenumbers.format_number(x, phonenumbers.PhoneNumberFormat.E164)
row[13] = phonenumbers.format_number(y, phonenumbers.PhoneNumberFormat.E164)
except:
continue
writer = csv.writer(open("base_new.csv", 'w'))
for row in data:
writer.writerow(row)
Some rows in comment "#LOOK HERE!" -in code are empty in my file. So this library phone numbers throws an exception. And i am struggling with fixing it.
Here is the example of exception from their page
>>> z = phonenumbers.parse("02081234567", None) # no region, no + => unparseable
Traceback (most recent call last):
File "phonenumbers/phonenumberutil.py", line 2350, in parse
"Missing or invalid default region.")
phonenumbers.phonenumberutil.NumberParseException: (0) Missing or invalid default region.
>>> z = phonenumbers.parse("gibberish", None)
Traceback (most recent call last):
File "phonenumbers/phonenumberutil.py", line 2344, in parse
"The string supplied did not seem to be a phone number.")
phonenumbers.phonenumberutil.NumberParseException: (1) The string supplied did not seem to be a phone number.
So(because i wanted program to still work through wrong numbers, i made TRY/Except and added continue. But it turned our that either variable x gives exception and num2 is skipped, or vice versa) It is such a struggle for me.
Please advise, how can handle exceptions properly and what to add, so my script could Fix both x AND num2 in EVERY row?
Upvotes: -1
Views: 717
Reputation: 180225
Your exception handlers should be just around the x = phonenumbers.parse
and num= = phonenumbers.parse
. When an exception is caught, simply set x
or num
to your desired alternative value.
Upvotes: 0