海上月明

          editer by sun
          posts - 162, comments - 51, trackbacks - 0, articles - 8
             :: 首頁 :: 新隨筆 ::  :: 聚合  :: 管理

          讀寫配置文件 by limodou

          Posted on 2008-01-28 22:36 pts 閱讀(247) 評論(0)  編輯  收藏 所屬分類: Python
          讀寫配置文件 by limodou

          下面是我根據(jù)sakulagi的思路改寫的程序:

          #! /usr/bin/python

          import os
          import sys

          class Ini:
              """ Assume that property file is "ARG=VALUE" format and no space is allowed on either side of \"=\" """
              def __init__(self, pfile):
                  self.items = {}
             
                  for line in file(pfile):
                      line = line.strip()
                      if not line: continue
                      if line.startswith('#'): continue
                      key, value = line.split('=', 1)
                      self.items[key.strip()] = value.strip()
             
              def getdict(self):
                  return self.items


          if __name__ == "__main__":
              print "Self Test Begin"
              # Generate the test file
              if len(sys.argv) == 1:
                  os.system("echo # Comment >; test.properties"
                  os.system("echo LOCK=true >;>; test.properties"
                  os.system("echo TEST.config.1=234 >;>; test.properties"
                  pf = Ini("test.properties";
              else:
                  pf = Ini(sys.argv[1])
              print pf.getdict()

          這里最后我的生成test.properties與原程序不同,因?yàn)榘l(fā)現(xiàn)在里面的雙引號也輸出到文件中去了,因此我去掉了。


          Powered by ScribeFire.

          主站蜘蛛池模板: 都兰县| 乐昌市| 类乌齐县| 康保县| 西青区| 铅山县| 亚东县| 沁源县| 利津县| 靖远县| 昔阳县| 尼勒克县| 象山县| 左云县| 灵丘县| 勐海县| 竹溪县| 梁山县| 女性| 乐昌市| 达州市| 萝北县| 丰原市| 永平县| 凤阳县| 凌云县| 灌云县| 楚雄市| 大庆市| 固始县| 西和县| 佳木斯市| 海口市| 洛川县| 彰化县| 新巴尔虎左旗| 罗江县| 柳州市| 彝良县| 南和县| 阿尔山市|