python编程格式,用Python编写格式正确的文本

In Python, I'm writing to a text file with code like:

f.write(filename + type + size + modified)

And of course the output looks really ugly:

C:/Config/ControlSet/__db.006 file 56 KB 2012-Apr-30 10:00:46.467 AM

C:/Config/ControlSet dir 68881 KB 2012-Apr-30 10:00:46.396 AM

C:/Config/DataStore.avlocate file 0 KB 2012-Apr-30 09:57:42.440 AM

C:/Config/DataStoreLocate.bak file 0 KB 2012-Apr-30 09:57:42.470 AM

C:/Config/DeviceConnections/devconn.bak file 41 KB 2012-Apr-30 10:39:50.181 AM

C:/Config/DeviceConnections/devconn.cfg file 41 KB 2012-May-29 10:12:45.288 AM

But I want to align the entries so it looks like this:

C:/Config/ControlSet/__db.006 file 56 KB 2012-Apr-30 10:00:46.467 AM

C:/Config/ControlSet dir 68881 KB 2012-Apr-30 10:00:46.396 AM

C:/Config/DataStore.avlocate file 0 KB 2012-Apr-30 09:57:42.440 AM

C:/Config/DataStoreLocate.bak file 0 KB 2012-Apr-30 09:57:42.470 AM

C:/Config/DeviceConnections/devconn.bak file 41 KB 2012-Apr-30 10:39:50.181 AM

C:/Config/DeviceConnections/devconn.cfg file 41 KB 2012-May-29 10:12:45.288 AM

My issue is similar to this question except I don't know how long the filenames will be beforehand. How should I approach this?

解决方案

If you can get a list of all filenames first, then you could do something like:

max_width = max(len(filename) for filename in filenames)

for filename in filenames:

f.write(filename.ljust(max_width+1)+..whatever else..)

If you can't get a list of all filenames first, then there's no way to make sure that everything will line up, because there's no way to know if you'll later get a file whose name is really long.

In a case like this, though, I would usually just assume that N columns is generally sufficient, for some N, in which case you can just do something like:

f.write('%-40s %6s %10s %2s\n' % (filename, type, size, modified))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值