'How to get all password values from all jsons and write it to a csv?

This is my code below. I'm loading a list of jsons from path_to_oldjson and then writing that list to a csv. I'm now trying to do the same with the password values inside the json files. I'm able to write passwords into it. But its only writing the last password from the json to the csv, not the matching password to the relevant json. How do I fix this?

Current code:

        path_to_oldjson = Path('C://Old Configs//')
        oldjsons = [file.name for file in path_to_oldjson.rglob("*.*")]
        path_to_newjson ='C://Encoded Configs//'

        #list1 = [1,2,3,4,5]

        # this finds our json files
        json_files = [pos_json for pos_json in os.listdir(path_to_oldjson) if pos_json.endswith('.json')]

        jsons_data = pd.DataFrame(columns=['Non Encoded Password'])


        def encode_password(obj):
            if 'password' in obj:

                listpasswords = obj['password']
                jsons_data.loc[index] = [listpasswords]
                print('Old password: ' + listpasswords)
                text = listpasswords
                sample_string_bytes = text.encode('ascii')
                base64_bytes = base64.b64encode(sample_string_bytes)
                finalpassword64password = base64_bytes.decode('ascii')
                obj['password'] = finalpassword64password
                print('New Enyctped  updated: ' + finalpassword64password)

                df = pd.DataFrame({"HotelName": oldjsons, "Oldpasswords": text,"Newpassword": finalpassword64password})
                df.to_csv('test.csv', index=False)

            return obj

        for index, js in enumerate(json_files):
            with open(os.path.join(path_to_oldjson, js)) as json_file:
                json_text = commentjson.load(json_file, object_hook=encode_password)
                with open(os.path.join(path_to_newjson, js),'w') as f:
                    commentjson.dump(json_text,f,indent = 4) #updates the password  
                 
        print('finished')

Current csv output:

HotelName,Oldpasswords,Newpassword
hotel1.json,testpass1,newpass1
hotel2json,testpass1,newpass1
hotel3.json,testpass1,newpass1
hotel4json,testpass1,newpass1

Execpted csv output:

HotelName,Oldpasswords,Newpassword
hotel1.json,testpass1,newpass1
hotel2json,testpass2,newpass2
hotel3.json,testpass3,newpass3
hotel4json,testpass4,newpass4


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source