加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

如何在Python中使用.write()两个项,一个零和一个迭代器?

发布时间:2020-12-20 13:50:41 所属栏目:Python 来源:网络整理
导读:我可能在这里有一个简单的格式化问题 – 我想做一些像hrOut.write(‘0′,i)这样的事情,以便为一个时间戳添加/添加一个零到’i’,但我不知道正确的语法.我的代码如下.谢谢你们. hrIn = open('HrsInput.csv')hrOut = open('HrsOutput.csv','wt')for i in hrIn:
我可能在这里有一个简单的格式化问题 – 我想做一些像hrOut.write(‘0′,i)这样的事情,以便为一个时间戳添加/添加一个零到’i’,但我不知道正确的语法.我的代码如下.谢谢你们.

hrIn = open('HrsInput.csv')
hrOut = open('HrsOutput.csv','wt')

for i in hrIn:
    if len(i) < 5:    
        hrOut.write('0',i)
    else:
        hrOut.write(i)

hrIn.close()
hrOut.close()

**我最终发现填充技术有效.我可能被excel欺骗了,因为在记事本中填充显示出来.

hrIn = open('HrsInput.csv')
hrOut = open('HrsOutput.csv','wt')

for i in hrIn:   
    hrOut.write("{}n".format(i.rstrip().zfill(5)))

hrIn.close()
hrOut.close()

解决方法

使用str.format:

hrOut.write('0{}'.format(i))

或删除if / else和pad:

for i in hrIn:   
    hrOut.write("{}n".format(i.rstrip().zfill(5)))

zfill只会为您的时间添加零,有四个字符:

In [21]: "12:33".zfill(5)
Out[21]: '12:33'

In [22]: "2:33".zfill(5)
Out[22]: '02:33'

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读