Python exceptIndex 问题?

标签 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])

但是以正确的格式打印它,有人可以提供帮助吗?

最佳答案

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

相反,您可以将 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

关于Python exceptIndex 问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24666102/

相关文章:

python - 使用 Django ORM 编写元组搜索

python - 类型错误 : Format Requires Mapping

python - tf.transform : add preprocessing to Keras model?

python - 运输优化(PuLP)

python - Django:GET css 返回 404?

python - 如何在 emacs 中从 gdb 获取输入(使用 python 脚本)

python - 使用 keras 的 sk-learn API 时出错

python - httplib.InvalidURL : nonnumeric port:

python - Django:为特定模型的 `QuerySet`对象提供自定义过滤方法

python - 如何将文件名传递给从 Python 执行的外部命令?