分享

每周一题——读写配置文件。 Python讨论区/精华帖...

 accesine 2005-09-07
下面是我根据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与原程序不同,因为发现在里面的双引号也输出到文件中去了,因此我去掉了。

下面是我根据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与原程序不同,因为发现在里面的双引号也输出到文件中去了,因此我去掉了。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多