0

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?

flash
  • 1,455
  • 11
  • 61
  • 132
  • What have you tried so far and what went wrong? This can be done inside a simple loop. – Selcuk May 04 '18 at 00:27
  • Any reason the config file is stored as `=` vs. `=`. If you can store as the latter then you can use `ConfigParser` to directly read it in and then simply `config[]` would give you `clientid` – AChampion May 04 '18 at 01:17

1 Answers1

1

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.

Thirsty_Crow
  • 133
  • 1
  • 6