Reading specific lines only

后端 未结 28 1520
天命终不由人
天命终不由人 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:40
    with open("test.txt", "r") as fp:
    lines = fp.readlines()
    print(lines[3])
    

    test.txt is filename prints line number four in test.txt

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

    Reading from specific line:

    n = 4   # for reading from 5th line
    with open("write.txt",'r') as t:
         for i,line in enumerate(t):
             if i >= n:             # i == n-1 for nth line
                print(line)
    
    0 讨论(0)
  • 2020-11-22 05:45

    You can do a seek() call which positions your read head to a specified byte within the file. This won't help you unless you know exactly how many bytes (characters) are written in the file before the line you want to read. Perhaps your file is strictly formatted (each line is X number of bytes?) or, you could count the number of characters yourself (remember to include invisible characters like line breaks) if you really want the speed boost.

    Otherwise, you do have to read every line prior to the line you desire, as per one of the many solutions already proposed here.

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

    If the file to read is big, and you don't want to read the whole file in memory at once:

    fp = open("file")
    for i, line in enumerate(fp):
        if i == 25:
            # 26th line
        elif i == 29:
            # 30th line
        elif i > 29:
            break
    fp.close()
    

    Note that i == n-1 for the nth line.


    In Python 2.6 or later:

    with open("file") as fp:
        for i, line in enumerate(fp):
            if i == 25:
                # 26th line
            elif i == 29:
                # 30th line
            elif i > 29:
                break
    
    0 讨论(0)
  • 2020-11-22 05:48

    Here's my little 2 cents, for what it's worth ;)

    def indexLines(filename, lines=[2,4,6,8,10,12,3,5,7,1]):
        fp   = open(filename, "r")
        src  = fp.readlines()
        data = [(index, line) for index, line in enumerate(src) if index in lines]
        fp.close()
        return data
    
    
    # Usage below
    filename = "C:\\Your\\Path\\And\\Filename.txt"
    for line in indexLines(filename): # using default list, specify your own list of lines otherwise
        print "Line: %s\nData: %s\n" % (line[0], line[1])
    
    0 讨论(0)
提交回复
热议问题