【发布时间】:2012-08-12 07:37:33
【问题描述】:
我正在编写一个脚本,将一个大的 CSV 文件分块成更小的分块文件。它交叉引用一个日志文件,该文件包含最后一个被分块的时间戳,因此只有晚于记录时间的时间戳被写入/分块。
csv 文件的第一列有一个%Y%m%d %H%M%S 格式的时间戳。 CSV 文件还有四行我在脚本中不需要/不需要的标题信息,rows in ts_pre 子句将其删除。
log_lookup() 函数只是从日志中提取我正在查看的特定电台的 CSV 文件的最后一个时间序列。显然,我正在与六个不同的站点合作,它们都有不同的信息列,除了它们都具有我在第二段中描述的相同结构。
部分脚本为:
import csv, sys, datetime
def log_lookup():
global STN_num
global STN_date
with open('/home/log.txt', 'rb') as open_log:
log_file = csv.reader(open_log)
for row in log_file:
for item in row:
STN_date.append(item)
if find == 'STN_1':
return STN_date[1]
if find == 'STN_2':
return STN_date[2]
if find == 'STN_3':
return STN_date[3]
if find == 'STN_4':
return STN_date[4]
if find == 'STN_5':
return STN_date[5]
if find == 'STN_6':
return STN_date[6]
def get_ts(line):
print line[0:19]
return datetime.datetime.strptime(line, "%Y/%m/%d %H:%M:%S")
def main():
log = str(log_lookup()) #useful for knowing when to start chunking
log_datetime = datetime.datetime.strptime(log, "%Y/%m/%d %H:%M:%S")
with open(sys.argv[1], 'rb') as open_file:
ts_from_file = csv.reader(open_file)
for genrows in ts_from_file:
ts_pre.append(genrows)
for rows in ts_pre:
if rownum < 4:
ts_pre.pop()
rownum += 1
else:
for line in rows:
if get_ts(line) > log_datetime:
timeseries.append(line)
日志文件很简单:
0
2011/10/06 18:40:00
2012/06/27 13:25:00
1900/01/01 00:00:00
2011/08/03 14:55:00
2012/06/27 20:05:00
2011/10/03 19:25:00
... 以 0 作为占位符。 (很明显我不是程序员吗?)
一个示例 CSV 文件如下所示:
"2011/10/03 16:40:00",0,0
"2011/10/03 16:45:00",1,0
"2011/10/03 16:50:00",2,0
"2011/10/03 16:55:00",3,0
ts_line(line) 函数时我遇到的错误是它说 line[0:19] 是:
2011/10/03 16:40:00
0
函数返回0,Python 抛出此错误:
ValueError: time data '0' does not match format '%Y/%m/%d %H:%M:%S'
我已验证返回的0 是 CSV 文件中的第二项,但我对 Python 为什么在我的切片选择中返回它感到困惑。有人可以向我解释为什么它会返回该值以及我需要做什么才能让时间戳与日志时间戳进行比较?
对于额外的功劳,任何关于编码/风格的建议都会受到赞赏和/或建议以更好的方式完成我正在做的事情。我正在查看的 CSV 文件非常大(~8 MB),所以效率越高越好。
【问题讨论】: