【问题标题】:Skipping line as parsing - Python CSV跳过行作为解析 - Python CSV
【发布时间】:2020-11-05 13:50:54
【问题描述】:

目前我的日志文件的结构是这样的。

Time: 13 s. Month: jul Date: 5
Money: 50. Tires: 0 Rent: yes 
Time: 13 s. Month: jul Date: 5
Money: 50. Tires: 0 Rent: yes 
Time: 13 s. Month: jul Date: 5
Money: 50. Tires: 0 Rent: yes 

我正在编写一个将其转换为 csv 的 python 脚本。

import csv
with open('output.csv', 'w') as out_file, open('stats.log', 'r') as in_file:
    writer = csv.writer(out_file)
    writer.writerow(['month', 'rent'])

    for line in in_file:
        columns = line[:-1].split(' ')
        columns[6] = ' '.join(columns[6:])
        writer.writerow(columns[:7])

我正在尝试为月和租金创建两列,但由于我是根据行来查看它,所以我无法弄清楚如何跳过行或只是寻找关键字来创建 csv文件。

【问题讨论】:

  • 您要跳过哪些行?你在找什么关键词?
  • 我只是想用 MONTH 和 RENT 的数据去掉它,而忽略其他所有内容

标签: python bash csv logging


【解决方案1】:

试试这个:

import csv
with open('output.csv', 'w') as out_file, open('stats.log', 'r') as in_file:
    writer = csv.writer(out_file)
    writer.writerow(['month', 'rent'])
    lines = in_file.rstrip().split("\n")
    lines = [lines[x*2]+lines[x*2+1] for x in range(int(len(lines)/2))]
    
    for line in lines:
        columns = line.rstrip().split()
        writer.writerow([columns[1],columns[5]])

【讨论】:

  • 您好,是的,但由于我要查找的数据位于两个不同的行(月和租金)中,CSV 文件创建了点,但每次在电子表格中跳过一行
  • 或者说我只是想阅读月份数据。如何从日志文件中跳过一行数据。
猜你喜欢
  • 1970-01-01
  • 2014-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-12
相关资源
最近更新 更多