2012-03-19 40 views
1

我正在开发一个python脚本,该脚本可以打开日志文件,将特定信息写入新的csv文件,然后比较每个行为之间的时间差日志文件。我遇到的问题是,我需要设法在第一次写入过程中关闭新csv文件后添加时差。这是我迄今为止的那部分内容。将行添加到CSV文件而不更改其格式(Python)

final_file = open('FinalLogFile.csv', 'w') 
temp_logfile = csv.reader(open('tempLogFile.csv', 'rb'), delimiter="\t") 

fmt = '%Y-%m-%d %H:%M:%S.%f' 
row_count = 0 

#find the time between each action and write it to the new file 
#transfer actions from temp file to final file 
for row in temp_logfile: 
    time = (row[0] + " " + row[1]) 
    timestamp = strptime(time, fmt) 
    current_value = mktime(timestamp) 

    row_count+=1 
    if row_count == 1: 
     previous_value = current_value 

    #print ("%s - %s" %(current_value, previous_value)) 
    total_value = current_value - previous_value 

    final_file.write('%s, %s' %(row,total_value) + '\n') 

    previous_value = current_value 
final_file.close() 

#remove the temp logfile 
rm_command = "rm ~/log_parsing/tempLogFile.csv" 
os.system(rm_command) 

现在,它在每一行的末尾添加时间,但是,格式是从原来的完全不同,它增加了每个字母,空格字符和数字之间的逗号。有没有办法保持临时文件的原始格式,或只是将时间添加到原始临时文件中而不创建新文件?

感谢您的帮助!

回答

0

每个row返回的csv.reader是一个列表。
随着final_file.write('%s, %s' % (row,total_value) + '\n')你写:

  1. 列表(其再版是逗号分隔)
  2. 时差
  3. 新行

但你可以做到这一切在一步使用csv.writer

final_file = csv.writer(open('FinalLogFile.csv', 'wb'), delimiter="\t") 
... 
    row.append(total_value) 
    final_file.writerow(row) 
... 
+0

感谢您的快速响应!我刚刚尝试了您的建议,并且出现此错误“_csv.Error:预期的顺序” – user1186173 2012-03-19 20:39:02

+0

@ user1186173:我的错误。 '.append()'返回'None'不是列表本身。我更新了这个例子。 – bernie 2012-03-19 20:45:22

+0

那肯定工作得好多了,但是现在它并没有真的进入下一行。 – user1186173 2012-03-19 20:45:49

相关问题