在Python中格式化CSV文件的输出

在Python中格式化CSV文件的输出

本文介绍了在Python中格式化CSV文件的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Python中创建一个非常基本的地址簿程序。我从CSV文件中获取联系人数据,其内容如下所示:

  

您可以使用格式你的输出。例如,

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

输出:

 姓名电话公司电子邮件
Elon Musk 454-6723 SpaceX [email protected]
Larry页面853-0653 Google [email protected]
Tim Cook 133-0419 Apple tcook @ apple。 com
Steve Ballmer 456-7893开发者! [email protected]

您可以阅读更多关于。 < 符号左对齐文本,数字指定字符串的宽度。每个 {} 可以在冒号之前包含位置参数: - 如果省略,字符串将出现在code> row 。


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:

Name,Phone,Company,Email
Elon Musk,454-6723,SpaceX,[email protected]
Larry Page,853-0653,Google,[email protected]
Tim Cook,133-0419,Apple,[email protected]
Steve Ballmer,456-7893,Developers!,[email protected]

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:

Name:        Phone:        Company:        Email:
Elon Musk    454-6723      SpaceX          [email protected]

My current code is as follows:

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

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

['Name', 'Phone', 'Company', 'Email']
['Elon Musk', '454-6723', 'SpaceX', '[email protected]']
['Larry Page', '853-0653', 'Google', '[email protected]']
['Tim Cook', '133-0419', 'Apple', '[email protected]']
['Steve Ballmer', '456-7893', 'Developers!', '[email protected]']

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.

解决方案

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               [email protected]
Larry Page       853-0653         Google               [email protected]
Tim Cook         133-0419         Apple                [email protected]
Steve Ballmer    456-7893         Developers!          [email protected]

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.

这篇关于在Python中格式化CSV文件的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 09:48