Formatting output of CSV file in Python

前端 未结 1 627
夕颜
夕颜 2021-02-14 05:21

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:

1条回答
  •  深忆病人
    2021-02-14 05:45

    You could use format to left justify your 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  
    

    You can read more about format here. The < symbol left-aligns the text, and the number specifies the width of the string. Each {} can include a positional argument before the colon : - if they are omitted, the strings will appear in the order of the arguments in the unpacked list row.

    0 讨论(0)
提交回复
热议问题