Reading specific lines only

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

    I prefer this approach because it's more general-purpose, i.e. you can use it on a file, on the result of f.readlines(), on a StringIO object, whatever:

    def read_specific_lines(file, lines_to_read):
       """file is any iterable; lines_to_read is an iterable containing int values"""
       lines = set(lines_to_read)
       last = max(lines)
       for n, line in enumerate(file):
          if n + 1 in lines:
              yield line
          if n + 1 > last:
              return
    
    >>> with open(r'c:\temp\words.txt') as f:
            [s for s in read_specific_lines(f, [1, 2, 3, 1000])]
    ['A\n', 'a\n', 'aa\n', 'accordant\n']
    

提交回复
热议问题