【问题标题】:How can I skip first line reading from stdin?如何跳过标准输入的第一行读取?
【发布时间】:2014-07-17 06:42:09
【问题描述】:
 while 1:
     try:
         #read from stdin
         line = sys.stdin.readline()
     except KeyboardInterrupt:
         break
     if not line:
         break
     fields = line.split('#')
     ...

如何跳过stdin 的第一行阅读?

【问题讨论】:

    标签: python stdin


    【解决方案1】:
    infile = sys.stdin
    next(infile) # skip first line of input file
    for line in infile:
         if not line:
             break
         fields = line.split('#')
         ...
    

    【讨论】:

    • 这比我的例子好多了:) 出于好奇:为什么不直接做next(sys.stdin)?为什么要给它取别名?
    • @exhuma,我认为它更具可读性。其他人可能喜欢在任何地方使用sys.stdin。只是个人喜好(直到您需要重构代码以便能够选择性地从其他地方读取)
    • 如果你想预见重构,我会将它放入一个以文件为参数的函数中;)——但我明白你的意思:)
    【解决方案2】:

    您可以使用enumerate 函数来实现:

    for place, line in enumerate(sys.stdin):
        if place: # when place == 0 the if condition is not satisfied (skip first line) 
            ....
    

    enumerate的文档。

    【讨论】:

    • 我发现为此使用enumerate 很浪费(只是直觉)。它看起来不对。有更清洁的解决方案。我发现@gnibbler 是迄今为止最pythonic 的解决方案。
    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 2011-06-02
    • 2020-02-25
    • 2020-03-07
    • 1970-01-01
    • 2023-03-17
    • 2011-10-21
    相关资源
    最近更新 更多