- 论坛徽章:
- 0
|
每周一题——读写配置文件。
爱学习的新手来了
俺是彻底的新手。如果写的有问题,不要笑
- #! /usr/bin/python
- import os
- import sys
- class property:
- """ Assume that property file is "ARG=VALUE" format and no space is allowed on either side of \"=\" """
- def __init__(self, pfile):
- f = open(pfile, "r")
- linel = f.readlines()
- list = map(self.split, linel)
- #remove comments marker
- if list.count(None) >; 0:
- list.remove(None)
- self.dict = dict(tuple(list))
- def split(self, str):
- # remove newline
- str = str.strip("\n")
- # remove blank spaces
- str = str.strip()
- # Treat comments separately
- if str.startswith("#"):
- r = None
- else:
- # At most 2 parts
- r = str.split("=", 1)
- r = map(self.stripbs, r)
- return r
- def stripbs(self, str):
- return str.strip()
- def getdict(self):
- return self.dict
- 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 = property("test.properties");
- else:
- pf = property(sys.argv[1])
- print pf.getdict();
复制代码 |
|