Reading specific lines only

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

提交回复
热议问题