如何在.csv文件中获取特定行并避免重复?

时间:2017-01-23 11:59:36

标签: python powershell csv

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

  1. 在B栏中,我只需要获得“错误”的内容。

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

  3. 示例:

    ## Level ##    ## Message ##
    
    Error      ---------------       blah blah
    
    
    ----------

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

    Param($Work)
    
    if (!$Work) {
        powershell -NoExit -File $MyInvocation.MyCommand.Path 1
        return
    }
    
    Select-String -pattern "ERROR" -path .\log.log
    

2 个答案:

答案 0 :(得分:0)

不太确定列'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))

答案 1 :(得分:0)

试试这个

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