【问题标题】:Python - Time conversion in a loop through a .csv columnPython - 通过 .csv 列循环进行时间转换
【发布时间】:2014-07-09 12:58:57
【问题描述】:

我有一个大的 .csv 文件,其中存储了一些录音中的数据。其中一个字段包含录制的时间,我需要进行转换以便以后使用它们进行操作。

*Col 0, hh:mm:ss, col 2, col 3,...*

我知道如何使用单个值进行时间转换,它使用单个值。这行得通,

import decimal
from datetime import datetime

time = "14:55:36.629"
(hour,min,sec) = time.split(':')
result = int(hour) * 3600 + int(min) * 60 + float(sec)
decimal.Decimal(result)

但我无法在循环中插入它

with open('input.csv', 'r') as inf, open('output.csv','wb') as outf:
    for row in inf:
        t = row[1]
        (h,m,s) = row[1].split(':') # Error here
        result = int(h) * 3600 + int(m) * 60 + float(s)
        decimal.Decimal(result)
    outcsv = csv.writer(outf, delimiter=',')

我坚持转换,但同时我不确定以后是否能够将信息写入另一个文件。如何将所有值转换并解析为一列?

我也可以覆盖原始文件而不是打开另一个文件并在那里写入信息。

【问题讨论】:

  • 您没有以 CSV 格式读取文件 - row[1]单个字符

标签: python loops csv time


【解决方案1】:

您需要实际读取输入文件as CSV。比较和对比,用一些虚拟数据:

>>> demo = ['id,time,data', '1,14:17:33,7', '2,14:17:34,10']

直接遍历“文件”:

>>> for row in demo:
    row[1]


'd'
','
','

迭代读取为 CSV:

>>> import csv
>>> for row in csv.reader(demo):
    row[1]


'time'
'14:17:33'
'14:17:34'

或者,让你的代码更清晰(假设你有一个标题行):

>>> for row in csv.DictReader(demo):
    row['time']


'14:17:33'
'14:17:34'

【讨论】:

    【解决方案2】:

    此解决方案将输出写入不同的文件。如果要在同一个文件上写入,则需要将输入文件作为行列表加载和处理,然后写入同一个文件。

    import csv
    with open('input.csv', 'r') as inf, open('output.csv','wb') as outf:
        reader = csv.reader(inf, delimiter=',')
        writer = csv.writer(outf, delimiter=',' )
        for row in reader:
            t = row
            (h,m,s) = t[1].split(':')
            result = int(h) * 3600 + int(m) * 60 + float(s)
            t[1] = result
            writer.writerow(t)
    

    【讨论】:

    • 谢谢解答,但是转换后,我应该怎么写成列表呢?我设法写了初始信息,但不是在操作之后。
    猜你喜欢
    • 1970-01-01
    • 2019-03-28
    • 2017-10-06
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    相关资源
    最近更新 更多