Reading specific lines only

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

    To print desired line. To print line above/below required line.

    def dline(file,no,add_sub=0):
        tf=open(file)
        for sno,line in enumerate(tf):
            if sno==no-1+add_sub:
             print(line)
        tf.close()
    

    execute---->dline("D:\dummy.txt",6) i.e dline("file path", line_number, if you want upper line of the searched line give 1 for lower -1 this is optional default value will be taken 0)

提交回复
热议问题