Search code examples
python-3.xtext-filesread-write

python function to read all descendant lines of a given line which are not empty


the function will take two parameters (line, txtfile) and should return all the descendant lines after the line parameter from txtfile which are not empty

for example the text file contains:

line1
line2

line3
line4
line5

the function should return line1line2 if line1 is given as parameter or line3line4line5 if line3 is given as parameter


Solution

  • def fun(line, filename):
      file = open(filename, 'r') 
      output=''
      empty=False
      for i in file:
        if(i.rstrip('\n')==line or empty):
          empty=True
          output+=i.rstrip('\n')
          if(i.rstrip('\n')==''):
            empty=False
      return output
    filename=input("Enter file name")
    line=input("Input line")
    output=fun(line,filename)
    print(output)