Home > Net >  How to read multiple text file at once and find particular text between two text?
How to read multiple text file at once and find particular text between two text?

Time:12-13

This code works fine if I operate with one text file at a time. But if I uncomment last three lines and comment print statement to operate this code with multiple files at once then this code is not working. It does not gives any error but also does not give any output!!

import pathlib

def extract_text(filename):
    start = "#patient_name').val('"
    end = "');$('#father_name"
    with open(filename, 'rt') as myfile:
        text = myfile.read()
        return text[text.find(start) len(start):text.rfind(end)]


print(extract_text('new.txt'))
    #patients = []
    #for filename in pathlib.Path('.').glob('*.txt'):
     #patients.append(extract_text(filename))

This are my temporary text files with the values I want in it enter image description here

This is the output if I use the code for one file at a time Anyone plz embed my images, I am yet not allowed, THANKS!

And this is the output when I use this code for multiple files! OUTPUT

Note: This code are not completely written by me. Someone helped me on my last question on stackoverflow

I have also another code which I got from geeksforgeeks but it is also not working!!!

CodePudding user response:

Please print the patients to get output.

import glob

def extract_text(filename):
    start = "#patient_name').val('"
    end = "');$('#father_name"
    with open(filename, 'rt') as myfile:
        text = myfile.read()
    myfile.close()
    return text[text.find(start) len(start):text.rfind(end)]


patients = []
for filename in glob.glob('./*.txt'):
    patients.append(extract_text(filename))
print(patients)

Can you try this.

CodePudding user response:

As @Bashi said in comment It was indentation error and the final working code here

import pathlib

def extract_text(filename):
    start = "#patient_name').val('"
    end = "');$('#father_name"
    with open(filename, 'rt') as myfile:
        text = myfile.read()
        return text[text.find(start) len(start):text.rfind(end)]

patients = []
for filename in pathlib.Path('.').glob('*.txt'):
    print(extract_text(filename))
  • Related