Search code examples
pythonjsonextracttext-extractionnotepad

How to i extract a particular parameter and it's data from multiple text files?


Suppose i have multiple files such as file1 file2 and file3 and consists of following data:

file1:

{"status":"succes","message":"User Found","error_code":"0","data":{"phone":0,"name":"Sanju Mehra","gender":"","tob":"","dob":"","pob":"","email":"sanjumehra.palasi@gmail.com"}

file2:

{"status":"succes","message":"User Found","error_code":"0","data":{"phone":0,"name":"Anil Kumar","gender":"","tob":"","dob":"","pob":"","email":"kumaranil12462@gmail.com"}

file3:

{"status":"succes","message":"User Found","error_code":"0","data":{"phone":89XXXXXXXX,"name":"Ashish Chauhan","gender":"male","tob":"12:30","dob":"10\/18\/94","pob":"ambala, haryana","email":"ashishchauhan1810@gmail.com"}

I'd like to extract name and phone number from these multipe file where i actually want to extract the data of a phone number and the data entered on name parameter.

Could you please tell me the possible ways with which i could do that?


Solution

  • The data in a file is looking like a dictionary format. Then the answer is as follows

    import os,sys        
    
    ws=r"C:\Users\xx\Desktop\dd"
    for root,dirs,files in os.walk(ws):
        for file1 in files:
            file_path=os.path.join(root,file1)
    
            file2 = open(file_path, "r", encoding="utf8") 
    
            data_string=file2.read()
            #Then the phone number is    
            phone_number=data_string['data']['phone']    
            #    Then the name is
            name=data_string['data']['name']    
            #like above you can access all keys and value from dictionary