【问题标题】:How to get specific line in a .csv file and avoid duplication?如何获取 .csv 文件中的特定行并避免重复?
【发布时间】:2017-06-07 22:26:31
【问题描述】:

我有一个 CSV 文件,其中有两件事:

  1. 在 B 列中,我只需要获取带有“ERROR”的内容。

  2. 完成此操作后,我需要从 G 列获取所有信息,同时避免重复。

例子:

##级别####消息##

错误 --------------- 呜呜呜


----------

我尝试使用 PowerShell,但 Python 也会被接受:

Param($Work)

if (!$Work) {
    powershell -NoExit -File $MyInvocation.MyCommand.Path 1
    return
}

Select-String -pattern "ERROR" -path .\log.log

【问题讨论】:

  • 请编辑和格式化帖子,以便 CSV 包含合理的示例数据。同时添加负面和正面结果。

标签: python powershell csv


【解决方案1】:

不太清楚列“b”和“g”的列索引是什么,但希望这会有所帮助。

您可以在documentation 中阅读有关 CSV 处理的更多信息

import csv

#where the final answer will be
extracted_info = []

with open('target.csv', 'r') as fd:
    csv_reader = csv.reader(fd)

    #Skip header
    next(csv_reader, None)

    #go through all rows
    for row in csv_reader:

        #Check if column b (looks like column 1?)
        if (row[0] == "ERROR"):
            #Get information from column 'G'
            extracted_info.append(row[3])

#Get unique values only by casting to set then re-casting to list
extracted_info = list(set(extracted_info))

【讨论】:

    【解决方案2】:

    试试这个

    import-csv "c:\temp\youfile.csv" | where Level -eq 'Error' | select ColumnNameForG -Unique
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-15
      • 2017-03-30
      • 2018-03-17
      • 2018-06-13
      • 2020-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多