Reading specific lines only

后端 未结 28 2108
天命终不由人
天命终不由人 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:31

    A fast and compact approach could be:

    def picklines(thefile, whatlines):
      return [x for i, x in enumerate(thefile) if i in whatlines]
    

    this accepts any open file-like object thefile (leaving up to the caller whether it should be opened from a disk file, or via e.g a socket, or other file-like stream) and a set of zero-based line indices whatlines, and returns a list, with low memory footprint and reasonable speed. If the number of lines to be returned is huge, you might prefer a generator:

    def yieldlines(thefile, whatlines):
      return (x for i, x in enumerate(thefile) if i in whatlines)
    

    which is basically only good for looping upon -- note that the only difference comes from using rounded rather than square parentheses in the return statement, making a list comprehension and a generator expression respectively.

    Further note that despite the mention of "lines" and "file" these functions are much, much more general -- they'll work on any iterable, be it an open file or any other, returning a list (or generator) of items based on their progressive item-numbers. So, I'd suggest using more appropriately general names;-).

提交回复
热议问题