海上月明

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

          日歷

          <2008年1月>
          303112345
          6789101112
          13141516171819
          20212223242526
          272829303112
          3456789

          Good Blogs

          搜索

          •  

          積分與排名

          • 積分 - 262953
          • 排名 - 216

          讀寫配置文件 by limodou

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

          下面是我根據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與原程序不同,因為發現在里面的雙引號也輸出到文件中去了,因此我去掉了。


          Powered by ScribeFire.

          主站蜘蛛池模板: 泾阳县| 冀州市| 茂名市| 印江| 绵竹市| 高密市| 利辛县| 剑川县| 彭泽县| 禄丰县| 三河市| 高密市| 洛阳市| 雅江县| 萨迦县| 北川| 德州市| 太康县| 镇平县| 肇州县| 栾川县| 齐齐哈尔市| 伊川县| 岳西县| 伊金霍洛旗| 屏东市| 普定县| 寿宁县| 融水| 鹿邑县| 涞源县| 威海市| 湾仔区| 峡江县| 平定县| 农安县| 文登市| 南澳县| 喜德县| 射洪县| 镇安县|