Reading specific lines only

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

    Fairly quick and to the point.

    To print certain lines in a text file. Create a "lines2print" list and then just print when the enumeration is "in" the lines2print list. To get rid of extra '\n' use line.strip() or line.strip('\n'). I just like "list comprehension" and try to use when I can. I like the "with" method to read text files in order to prevent leaving a file open for any reason.

    lines2print = [26,30] # can be a big list and order doesn't matter.
    
    with open("filepath", 'r') as fp:
        [print(x.strip()) for ei,x in enumerate(fp) if ei in lines2print]
    

    or if list is small just type in list as a list into the comprehension.

    with open("filepath", 'r') as fp:
        [print(x.strip()) for ei,x in enumerate(fp) if ei in [26,30]]
    

提交回复
热议问题