john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

file to dictionary properties file format equals skips comments

# 2012-12-13 johnpfeiffer
#class PropertiesReader():
"""For reading and writing from a config file (key = 'value')
"""

#  def __init__(self):


# FUNCTIONS ##############

def propertiesFileToDictionary( file_name ):
    file = open( file_name )
    key_value_dictionary = dict()

    for line in file:
      line = line.strip()
      if not line:
        continue
      if line[0] == '#':
        continue
      temp = line.split( '=' , 1 )  # split only once using the equals symbol
      key = temp[0].strip()
      value = temp[1].strip()
      key_value_dictionary[ key ] = value

    file.close()
    return key_value_dictionary



def propertiesFileToDictionary( file_name ):
    file = open( file_name )
    key_value_dictionary = dict()

    for line in file:
      line = line.strip()
      if not line:
        continue
      if line[0] == '#':
        continue
      temp = line.split( '=' , 1 )  # split only once using the equals symbol
      key = temp[0].strip()
      value = temp[1].strip()
      key_value_dictionary[ key ] = value

    file.close()
    return key_value_dictionary




# MAIN ###############

def main():
    print "start..."
    file_name = 'test.py'
    key_value_dictionary = propertiesFileToDictionary( file_name )
    keyList = key_value_dictionary.keys()

    print "\nKeys of properties found in " + file_name + ":\n"
    for key in keyList:
      print key

    oxygen_id = key_value_dictionary[ "oxygen_id" ]
    oxygen_password = key_value_dictionary[ "password" ]
    api_key = key_value_dictionary[ "api_key" ]

    print oxygen_id + " " + oxygen_password + " " + api_key


if __name__ == "__main__":
     main()

  • « shutdown halt poweroff
  • Perl file parse fstab get set properties file »

Published

Dec 14, 2012

Category

python

~142 words

Tags

  • comments 7
  • dictionary 4
  • equals 4
  • file 92
  • format 6
  • properties 8
  • python 180
  • skips 1
  • to 63