I'm working on a python script that opens a logfile, writes specific information to a new csv file and then compares the time difference between each action within the log file. The problem I'm having is that I need to figure a way to add the time difference to the new csv file after it was closed during the first writing process. This is what I have so far for that part.
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)
Right now, it does add the time at the end of each row, however, the formatting is completely different from the original and it adds comma's between each letter, space, character and number. Is there way to keep the original format of the temp file or just add the time into the original temp file without creating a new one?
Thanks for the help!
解决方案
Each row returned by csv.reader is a list.
With final_file.write('%s, %s' % (row,total_value) + '\n') you're writing:
a list (whose repr is comma-delimited)
the time difference
a new line
But you can do all of that in one step using csv.writer:
final_file = csv.writer(open('FinalLogFile.csv', 'wb'), delimiter="\t")
...
row.append(total_value)
final_file.writerow(row)
...