Python - Format Phone Numbers

PythonA small back story first, I overheard a conversation someone was having sitting next to me about a task they have to do.  The said each phone number in the company active directory has to be formatted a certain way for the new phone system.  They had been given a list from AD and there was a few thousand names.  He had started to go through the list and highlighting and pulling out the names of users that would need to be changed.  He had spent a couple of hours the previous evening going through the first couple of pages and how he was not looking forward to completing the laborious task.  I mentioned if he gave me 5 minutes I would be able to save you a good few hours.

The first of the quick wins was to show which of them had brackets in the number, which was the first thing to change.  I opened the csv file in Excel, cut out all the fields except for the name and phone number.  Saved the file, popped into Cygwin and grep "(" ad.csv, quick win there.  I gave him the list of names, he raised a call to the help desk so they could format these correctly.  Now the title is python - format phone numbers, so again a small piece of code to do this could be 

for line in open("ad.csv"):
  if "(" in line:
    print line,

Now onto the big one, he wanted all the numbers to be formatted +44 00 0000 0000 (mainly UK based number), so for this a little piece of code again, but needed to include a little regular expression to pull everything out not in the right format, be it extra spaces , etc.  The code for this was 

for line in open("Book1.csv"):
  if "+44" in line:
    if not re.match('\+\\d{2}\\s\d{2}\\s\d{4}\\s\d{4}',number):
     print line,


This gave him his list which he could then send on to the help-desk for them to change the numbers (there were a good few).  I was really happy I could help out, these few lines of code saved someone literally hours of manual work, he was happy as he was now in front of his project and he owes me a drink. 

I am always interested in your thoughts so if you have any comments or feedback then please feel free to add any comments, or you can mail me  here.

Related Posts Plugin for WordPress, Blogger... 


Drafts and Workflow - iOS Apps

Save space on your mac - iOS Upgrade files