flash
flash

Reputation: 1517

get key basis on value by reading property file in python?

I have a property file "holder.txt" like this which is in key=value format. Here key is clientId and value is hostname.

p10=machineA.abc.host.com
p11=machineB.pqr.host.com
p12=machineC.abc.host.com
p13=machineD.abc.host.com

Now I want to read this file in python and get corresponding clientId where this python script is running. For example: if python script is running on machineA.abc.host.com then it should give me p10 as clientId. Similarly for others.

import socket, ConfigParser

hostname=socket.getfqdn()
print(hostname)

# now basis on "hostname" figure out whats the clientId 
# by reading "holder.txt" file

Now I have worked with ConfigParser but my confusion is how can I get value of key which is clientId basis on what hostname it is? Can we do this in python?

Upvotes: 0

Views: 97

Answers (1)

Thirsty_Crow
Thirsty_Crow

Reputation: 133

You Need to read and store the holder file in memory as a dictionary:

mappings = {}
with open('holder.txt', 'r') as f:
    for line in f:
        mapping = line.split('=')
        mappings[mapping[1].rstrip()] = mapping[0]

Then perform a mapping every time you want to get clientId from hostname:

import socket, ConfigParser

hostname=socket.getfqdn()
clientId = mappings[hostname]

Hope that helps.

Upvotes: 1

Related Questions