Reading specific lines only

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

    A better and minor change for Alok Singhal's answer

    fp = open("file")
    for i, line in enumerate(fp,1):
        if i == 26:
            # 26th line
        elif i == 30:
            # 30th line
        elif i > 30:
            break
    fp.close()
    
    0 讨论(0)
  • 2020-11-22 05:27

    If you want to read specific lines, such as line starting after some threshold line then you can use the following codes, file = open("files.txt","r") lines = file.readlines() ## convert to list of lines datas = lines[11:] ## raed the specific lines

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 05:30

    You can do this very simply with this syntax that someone already mentioned, but it's by far the easiest way to do it:

    inputFile = open("lineNumbers.txt", "r")
    lines = inputFile.readlines()
    print (lines[0])
    print (lines[2])
    
    0 讨论(0)
  • 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;-).

    0 讨论(0)
  • 2020-11-22 05:31

    if you want line 7

    line = open("file.txt", "r").readlines()[7]
    
    0 讨论(0)
提交回复
热议问题