Reading specific lines only

后端 未结 28 1896
天命终不由人
天命终不由人 2020-11-22 05:08

I\'m using a for loop to read a file, but I only want to read specific lines, say line #26 and #30. Is there any built-in feature to achieve this?

Thanks

28条回答
  •  独厮守ぢ
    2020-11-22 05:30

    def getitems(iterable, items):
      items = list(items) # get a list from any iterable and make our own copy
                          # since we modify it
      if items:
        items.sort()
        for n, v in enumerate(iterable):
          if n == items[0]:
            yield v
            items.pop(0)
            if not items:
              break
    
    print list(getitems(open("/usr/share/dict/words"), [25, 29]))
    # ['Abelson\n', 'Abernathy\n']
    # note that index 25 is the 26th item
    

提交回复
热议问题