Reading specific lines only

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

    The quick answer:

    f=open('filename')
    lines=f.readlines()
    print lines[25]
    print lines[29]
    

    or:

    lines=[25, 29]
    i=0
    f=open('filename')
    for line in f:
        if i in lines:
            print i
        i+=1
    

    There is a more elegant solution for extracting many lines: linecache (courtesy of "python: how to jump to a particular line in a huge text file?", a previous stackoverflow.com question).

    Quoting the python documentation linked above:

    >>> import linecache
    >>> linecache.getline('/etc/passwd', 4)
    'sys:x:3:3:sys:/dev:/bin/sh\n'
    

    Change the 4 to your desired line number, and you're on. Note that 4 would bring the fifth line as the count is zero-based.

    If the file might be very large, and cause problems when read into memory, it might be a good idea to take @Alok's advice and use enumerate().

    To Conclude:

    • Use fileobject.readlines() or for line in fileobject as a quick solution for small files.
    • Use linecache for a more elegant solution, which will be quite fast for reading many files, possible repeatedly.
    • Take @Alok's advice and use enumerate() for files which could be very large, and won't fit into memory. Note that using this method might slow because the file is read sequentially.

提交回复
热议问题