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

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,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 cleaner and more readable, i.e. everything lined up in rows and columns, like this:

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)

Which naturally 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 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 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值