如何在python中检查包含制表符的列表?

如何在python中检查包含制表符的列表?,python,list,Python,List,我有一个data.csv文件,其中包含belwo内容,在这个文件的末尾,还有一些新行。现在我想读取这个文件,并从最后一行获取特定列的值 Connecting to the ControlService endpoint Found 3 rows. Requests List: --------------------------------------------------------------------------------------------------------------

我有一个data.csv文件,其中包含belwo内容,在这个文件的末尾,还有一些新行。现在我想读取这个文件,并从最后一行获取特定列的值

Connecting to the ControlService endpoint

Found 3 rows.
Requests List:
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Client ID                                                                   | Client Type                  | Service Type | Status               | Trust Domain              | Data Instance Name | Data Version | Creation Time              | Last Update                | Scheduled Time | 
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 REFRESH_ROUTINGTIER_ARTIFACTS_1465901168866                              | ROUTINGTIER_ARTIFACTS | SYSTEM       | COMPLETED            | RRA Bulk Client    | soa_server1       | 18.2.2.0.0  | 2016-06-14 03:49:55 -07:00 | 2016-06-14 03:49:57 -07:00 | ---            | 
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 500333443                                                          | CREATE                        | [FA_GSI]     | COMPLETED            | holder       | soa_server1       | 18.3.2.0.0  | 2018-08-07 11:59:57 -07:00 | 2018-08-07 12:04:37 -07:00 | ---            | 
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 500333446                                                          | CREATE                        | [FA_GSI]     | COMPLETED            | holder-test  | soa_server1       | 18.3.2.0.0  | 2018-08-07 12:04:48 -07:00 | 2018-08-07 12:08:52 -07:00 | ---            | 
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
现在我想解析上面的文件和最后一行的额外值。我想在最后一行中添加“客户端ID”和“信任域”列的额外值,即:

Client ID: 500333446
Trust Domain: holder-test
我得到了下面的python脚本,但由于csv文件末尾出现了新行而失败?如果我的csv文件没有任何新行,那么它可以正常工作

import csv

lines_to_skip = 4
with open('data.csv', 'r') as f:
    reader = csv.reader(f, delimiter='|')
    for i in range(lines_to_skip):
        next(reader)

    data = []
    for line in reader:
        if line[0].find("---") != 0:
            print line
            data.append(line)

print("{}={}".format(data[-1][0].replace(" ",""),data[-1][4].replace(" ","")))
如果我的csv文件末尾有一些新行,则在if块行中出现此错误:

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    if line[0].find("---") != 0:
IndexError: list index out of range

如果末尾有空行,
csv.reader
将为您提供空行,因此您必须编写代码来处理该问题。如果您只对每一行执行
行[0]
,即使是空的行,也会得到您所询问的异常

但在尝试检查
行[0]
之前,您只需检查
行是否为空:

if line:
    if line[0].find("---") != 0:
…或者更简洁地说:

if line and line[0].find("---") != 0:

如果末尾有空行,
csv.reader
将为您提供空行,因此您必须编写代码来处理该问题。如果您只对每一行执行
行[0]
,即使是空的行,也会得到您所询问的异常

但在尝试检查
行[0]
之前,您只需检查
行是否为空:

if line:
    if line[0].find("---") != 0:
…或者更简洁地说:

if line and line[0].find("---") != 0:

在处理该行之前,您应该去除所有不需要的字符,并确认它是您想要的行

你能做的是:

if line and line[0].strip(" \t") and not line[0].startswith("---"):
或者另一种方式:

if all([line, line[0].strip(" \t"), not line[0].startswith("---")]):
  • if line
    检查
    行是否为空列表,以便2。不会抛出错误
  • 行[0]。strip(“\t”)
    检查第一个值是否只包含不需要的字符
  • 不是第[0]行。startswith(“--”)与您的
    第[0]行相同。查找(“--”)=0

  • 在处理该行之前,您应该去除所有不需要的字符,并确认它是您想要的行

    你能做的是:

    if line and line[0].strip(" \t") and not line[0].startswith("---"):
    
    或者另一种方式:

    if all([line, line[0].strip(" \t"), not line[0].startswith("---")]):
    
  • if line
    检查
    行是否为空列表,以便2。不会抛出错误
  • 行[0]。strip(“\t”)
    检查第一个值是否只包含不需要的字符
  • 不是第[0]行。startswith(“--”)与您的
    第[0]行相同。查找(“--”)=0

  • 您可以尝试使用
    |
    将每一行拆分为一个字典列表,并仅打印最后一行的
    客户端ID
    信任域

    with open('data.txt') as f:
    
        # collect rows of interest
        rows = []
        for line in f:
            if '|' in line:
                items = [item.strip() for item in line.split('|')]
                rows.append(items)
    
        # first item will be headers
        headers = rows[0]
    
        # put each row into dictionary
        data = [dict(zip(headers, row)) for row in rows[1:]]
    
        # print out last row information of interest
        print('Client ID:', data[-1]['Client ID'])
        print('Trust Domain:', data[-1]['Trust Domain'])
    
    哪些产出:

    Client ID: 500333446
    Trust Domain: holder-test
    
    按照注释中的要求,如果您想打印
    500333446=支架测试
    ,您可以将最终打印顺序更改为:

    print('%s=%s' % (data[-1]['Client ID'], data[-1]['Trust Domain']))
    # 500333446=holder-test
    

    您可以尝试使用
    |
    将每一行拆分为一个字典列表,并仅打印最后一行的
    客户端ID
    信任域

    with open('data.txt') as f:
    
        # collect rows of interest
        rows = []
        for line in f:
            if '|' in line:
                items = [item.strip() for item in line.split('|')]
                rows.append(items)
    
        # first item will be headers
        headers = rows[0]
    
        # put each row into dictionary
        data = [dict(zip(headers, row)) for row in rows[1:]]
    
        # print out last row information of interest
        print('Client ID:', data[-1]['Client ID'])
        print('Trust Domain:', data[-1]['Trust Domain'])
    
    哪些产出:

    Client ID: 500333446
    Trust Domain: holder-test
    
    按照注释中的要求,如果您想打印
    500333446=支架测试
    ,您可以将最终打印顺序更改为:

    print('%s=%s' % (data[-1]['Client ID'], data[-1]['Trust Domain']))
    # 500333446=holder-test
    

    实际上,我正在将另一个脚本的输出保存在一个.csv文件中,因此它是这样的。我认为您不需要在任务中使用
    csv
    模块。只需像往常一样通过
    |
    字符简单拆分来解析此文件。实际上,我正在将另一个脚本的输出保存在一个.csv文件中,因此它是这样的。我认为您不需要使用
    csv
    模块来完成任务。只需像往常一样使用
    |
    字符进行简单拆分即可解析此文件。它仍然无法像我之前使用strip尝试的那样工作。我认为这行是一个列表,在这行的末尾,这是它打印出来的
    ['\t\t']
    @flash当然
    strip
    在列表上不起作用。但是如果行
    将。如果列表非空,则为true;如果列表为空,则为false。和
    行[0]。如果
    ['\t\t']
    ,则find(“--”)不会引发
    索引器
    <代码>行[0]
    是完全合法的,它的意思是
    '\t\t'
    行[0]。find(“--”)是完全合法的,返回
    -1
    。我尝试了你的建议,但仍然得到相同的错误。@flash另外,如果你的代码打印出来
    ['\t\t']
    ,那么那一行就没有问题。这是下一行,在那行之后。因为如果你得到了
    索引器
    ,你永远不会得到
    打印
    @flash,你需要给我们一个可以重现问题的提示。我所展示的将适用于你描述的问题。因此,假设你实际遇到的问题不是你描述的问题。这意味着没有人能猜到如何调试它。它仍然不能像我以前用strip试过的那样工作。我认为这行是一个列表,在这行的末尾,这是它打印出来的
    ['\t\t']
    @flash当然
    strip
    在列表上不起作用。但是如果行
    将。如果列表非空,则为true;如果列表为空,则为false。和
    行[0]。如果
    ['\t\t']
    ,则find(“--”)不会引发
    索引器
    <代码>行[0]
    是完全合法的,它的意思是
    '\t\t'
    行[0]。find(“--”)是完全合法的,返回
    -1
    。我尝试了你的建议,但仍然得到相同的错误。@flash另外,如果你的代码打印出来
    ['\t\t']
    ,那么那一行就没有问题。这是下一行,在那行之后。因为如果你得到了
    索引器
    ,你永远不会得到
    打印
    @flash,你需要给我们一个可以重现问题的提示。我所展示的将适用于你描述的问题。因此,假设你实际遇到的问题不是你描述的问题。这意味着没有人能猜到如何调试它