Reading specific lines only

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

提交回复
热议问题