向CSV文件添加行,而不更改其格式(Python)

2024-03-29 02:27:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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)

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

谢谢你的帮助!在


Tags: 文件csvthermtimevalue格式count
1条回答
网友
1楼 · 发布于 2024-03-29 02:27:41

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

  1. 列表(其repr以逗号分隔)
  2. 时差
  3. 新线

但您可以使用csv.writer一步完成所有这些:

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

相关问题 更多 >