python写入csv文件中添加行_向CSV文件中添加一行,而不更改其格式(Python)

1586010002-jmsa.png

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)

...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值