2012-03-19 95 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

相關問題