向CSV文件中添加一行,而不更改其格式(Python) [英] Adding a line to a CSV file, without changing its format (Python)

查看:2055
本文介绍了向CSV文件中添加一行,而不更改其格式(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python脚本打开日志文件,将特定信息写入新的csv文件,然后比较日志文件中每个操作之间的时间差异。我遇到的问题是,我需要一个方法来添加时间差异到新的csv文件,在它被关闭后,在第一个写入过程。这是我到目前为止这部分。

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?

感谢您的帮助! p>

Thanks for the help!

推荐答案

所返回的每一行 csv.reader 是一个列表。

使用 final_file.write('%s,%s'%(row,total_value)+'\\\
' code>您正在撰写:

Each row returned by csv.reader is a list.
With final_file.write('%s, %s' % (row,total_value) + '\n') you're writing:


  1. 一个列表(其repr用逗号分隔)

  2. 时差

  3. 一个新行

使用 csv.writer 在一个步骤中:

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

这篇关于向CSV文件中添加一行,而不更改其格式(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆