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

标签 python csv formatting conditional-statements

我这里可能有一个简单的格式问题 - 我想做一些像 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'

关于python - 如何在 Python 中 .write() 两个项目,一个零和一个迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30927627/

相关文章:

python - 将csv数据转换为dict的最佳方法

php - 使用 PHP 格式化 HTTP POST 请求中的数据

Emacs 组织模式 : How To Stop Total in Column View Showing Number of Days?

Python 2.7 使用函数的输入作为字符串和变量

Python 3.3 tkinter.filedialog.askopenfile() 留下无响应的 Tk 窗口

python - python 控制台和编辑器控制台中的不同行为

python - 包含使用 python 访问 C 数据结构的二进制文件

php - 从 Codeigniter 导出 CSV 文件

python - 操作 TSV 文件

python - 对 python 列表中的午餐项目进行排序