如何在Python中编写两个项目,一个零和一个迭代器?

2024-04-26 01:19:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我可能有一个简单的格式问题-我想做一些像hrOut.写入('0',i)以便在'i'前加一个0,这是一个时间戳,但我不知道正确的语法。我的代码在下面。谢谢大家。你知道吗

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()

Tags: csv代码inforclose格式时间语法
2条回答

只是个建议。不如这样做吧。你知道吗

(1)拆分“:”上的时间戳。例如:

"1:20".split(':')[:1]

这将返回1

(2)然后在python中使用zfill或sprintf等价物。比如:

"%02d" % (1,)

or use zfill on the split string (1) like : 

"1".zfill(3)

使用str.format格式地址:

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

或者移除if/else和pad:

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

zfill只为您的时间添加一个0,包含四个字符:

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

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

相关问题 更多 >

    热门问题