Eugene Nosenko Eugene Nosenko - 7 months ago 17
Python Question

Variables from txt file

I have a txt file that stores user IDs for

Selenium
tests that has something like this:

admin = ['admin@admin.com', 'password1234']
basicUser = ['basic@basic.com', 'password1234']


and would like to assign values for
admin
/
basicUser
from my txt file to my Python script, say something like this:

import file.txt
file = open('file.txt', 'r')
admin = file(admin)
basicUser = file(basicUser)


and whenever I call the
changePassword
method for my LoginPage

loginAs(admin)
changePassword('NEWpassword')


it would automatically update and save the txt file for next login.

I've been browsing the forums for hours now and cant find any good/elegant solution, any idea?

Answer

You can use .yaml file to store your users. It stores your date like json fotmat.

admin: {passwd: 123, user: admin@admin.com}
basicUser: {passwd: pass45, user: basic@basic.com}

To load your data from file:

import yaml
with open(FILE_PATH, 'r') as f:
   users_dict = yaml.load(f)
print(users_dict)
print(users_dict['admin'])
### {passwd: 123, user: admin@admin.com}
print(users_dict['admin']['passwd'])
### 123

After loading you can work with the data like a dict

To save your users data:

users_dict['admin']['passwd'] = 345

with open(FILE_PATH, 'w') as f:
   yaml.dump(users_dict, f)