Formatting output of CSV file in Python
<p>I am creating a very rudimentary "Address Book" program in Python.  I am grabbing contact data from a CSV file, the contents of which looks like the following example:</p>

<pre><code>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
</code></pre>

<p>I am trying to format the output so that it looks cleaner and more readable, i.e. everything lined up in rows and columns, like this:</p>

<pre><code>Name:        Phone:        Company:        Email:        
Elon Musk    454-6723      SpaceX          emusk@spacex.com
</code></pre>

<p>My current code is as follows:</p>

<pre><code>f = open("contactlist.csv")
csv_f = csv.reader(f)
for row in csv_f:
    print(row)
</code></pre>

<p>Which naturally due to lack of formatting, produces this, which still looks very unclean.</p>

<pre><code>['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']
</code></pre>

<p>Any tips on how to produce a cleaner output would be greatly appreciated, as I am beginner and I find all of this quite confusing.  Many thanks in advance.</p>

<p>You could use <code>format</code> to left justify your output. For example,</p>

<pre><code>f = open("contactlist.csv")
csv_f = csv.reader(f)
for row in csv_f:
    print('{:&lt;15}  {:&lt;15}  {:&lt;20} {:&lt;25}'.format(*row))
</code></pre>

<p>Output:</p>

<pre><code>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  
</code></pre>

<p>You can read more about <a href="https://docs.python.org/3/library/string.html#format-specification-mini-language" rel="nofollow">format here</a>. The <code>&lt;</code> symbol left-aligns the text, and the number specifies the width of the string. Each <code>{}</code> can include a positional argument before the colon <code>:</code> - if they are omitted, the strings will appear in the order of the arguments in the unpacked list <code>row</code>.</p>

python csv format