Python异常索引问题?

2024-05-29 04:31:35 发布

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

我有一个以制表符分隔的文件,其中有8列,例如具有以下上下文

Timestamp  Process   TID        Area            Category     EventID    Level           Message         Correlation 

06/21/2014 09:19:02.94  wsstracing.exe (0x068C)                         0x0698  SharePoint Foundation           Tracing Controller Service      5152    Information     Tracing Service started.     

06/21/2014 09:19:09.94  hostcontrollerservice.exe (0x063C)              0x0670  SharePoint Server               Unified Logging Service         b8fx    High            ULS Init Completed (hostcontrollerservice.exe, Microsoft.Office.Server.Native.dll)         

http://pastebin.com/f9dmrQtU

我目前拥有的代码

try:
    with open('text.log') as f:
        for l in f:
            print(l.strip().split("\t")[5], end=" "),
            print(l.strip().split("\t")[7], end=" "),
            print(l.strip().split("\t")[8], end="\n")
except IndexError:
    pass

给了我

EventID Message  Correlation

5152 Tracing Service started. Press any key to continue . . .

正如你所看到的,它在第一个条目之后就停止了,因为第8列已经没有任何内容了

当我需要的是打印的东西是一样的,即使在相关列下没有任何东西

EventID          Message              Correlation

1124             blahblahblah         blahblah

但是当我有以下代码

try:
    with open('text.log') as f:
        for l in f:
            print(l.strip().split("\t")[5], end=" "),
            print(l.strip().split("\t")[7])

但打印的格式是正确的,有人能提供帮助吗


Tags: messageserverserviceexeendsplitstripprint
3条回答

您的try被包装在循环中,因此一旦发生一个错误,try块就会停止执行并跳转到except块,这意味着不会再发生迭代

相反,您可以将try/except放在for循环中

with open('text.log') as f:
    for l in f:
        try:
            print(l.strip().split("\t")[5], end=" "),
            print(l.strip().split("\t")[7], end=" "),
            print(l.strip().split("\t")[8], end="\n")
        except IndexError:
            pass

但是,因为您知道不可能有第8个元素,所以它并不是真正的例外,如果您没有第6或第7个元素,它将隐藏错误

相反,试着用以下方法更好地控制你的逻辑:

with open('text.log') as f:
    for l in f:
        x = l.strip().split("\t")[5:] # Grab the elements you want...
        x.pop(1) #... but remove the element you don't
        print(" ".join(x)) # Now print them

当你做.strip()的时候,你会丢失后面的制表符,所以当你split()的时候,这行会短一些。除此之外,您还多次执行相同的操作

请尝试以下操作:

    with open('text.log') as f:
        for l in f:
            fields = l.split('\t')
            print(fields[5], end=" "),
            print(fields[7], end=" "),
            print(fields[8], end="\n")

你为什么要把整件事都包在try块里

with open('text.log') as f:
    for line in f:
        txt = l.strip().split("\t") # split once
    for col in (5,7,8):
        try:
            _end = "\n" if col == 8 else " "
            print(txt[col], end=_end)
        except IndexError:
            print("\t", end=_end) # print a blank column

相关问题 更多 >

    热门问题