python print files in the first few lines of a string

#!/usr/bin/python3

# -*- coding: UTF-8 -*-

import linecache # specifically supports reading large files, and supports a line reading library

 

# Print the first few lines (line does not contain this character resides) of a string

def List_h(List,filename,num):

    File = open(filename,"r")

    for nums, value in enumerate (File): content #enumerate traverse the line number and the line, but unms line number is the actual line number minus 1, you can use enumerate (file, 1) the line numbers start

        if str(List) in value:

            for ss in range (nums-num + 1, nums + 2,): ## ss subtracting the line number of unms num variable is incremented by 1 to 2 unms row number is incremented (because unms actual line number minus the line number 1)

                Content print (linecache.getline (filename, ss) .strip ()) # print the file filename variable ss line

        print ( "==================") # If there are multiple lines separated by ====

    File.close()

    return

# Print nfs file in the first five rows of the character 30001

List_h(30001,'nfs',5)

Guess you like

Origin blog.csdn.net/qq_35751770/article/details/93734402