Formatting CSV file output in Python

I am creating a very rudimentary Address Book program in Python. I am collecting contact data from a CSV file, the contents of which are as follows:

Name,Phone,Company,Email Elon Musk,454-6723,SpaceX, emusk@spacex.com Larry Page,853-0653,Google, lpage@gmail.com Tim Cook,133-0419,Apple, tcook@apple.com Steve Ballmer,456-7893,Developers!, sballmer@bluescreen.com 

I am trying to format the output so that it looks more understandable and readable, i.e. all lined up in rows and columns, for example:

 Name: Phone: Company: Email: Elon Musk 454-6723 SpaceX emusk@spacex.com 

My current code is as follows:

 f = open("contactlist.csv") csv_f = csv.reader(f) for row in csv_f: print(row) 

What is natural due to lack of formatting produces this which still looks very unclean.

 ['Name', 'Phone', 'Company', 'Email'] ['Elon Musk', '454-6723', 'SpaceX', ' emusk@spacex.com '] ['Larry Page', '853-0653', 'Google', ' lpage@gmail.com '] ['Tim Cook', '133-0419', 'Apple', ' tcook@apple.com '] ['Steve Ballmer', '456-7893', 'Developers!', ' sballmer@bluescreen.com '] 

Any advice on how to produce a cleaner result would be greatly appreciated as I begin, and I find it all quite confusing. Thank you very much in advance.

+7
python format csv
source share
1 answer

You can use format to align output. For example,

 f = open("contactlist.csv") csv_f = csv.reader(f) for row in csv_f: print('{:<15} {:<15} {:<20} {:<25}'.format(*row)) 

Output:

 Name Phone Company Email Elon Musk 454-6723 SpaceX emusk@spacex.com Larry Page 853-0653 Google lpage@gmail.com Tim Cook 133-0419 Apple tcook@apple.com Steve Ballmer 456-7893 Developers! sballmer@bluescreen.com 

Read more about here . The < character aligns the text to the left, and the number indicates the width of the line. Each {} may include a positional argument before the colon : - if they are omitted, the lines will be displayed in the order of the arguments in the unpacked list row .

+6
source share

All Articles