[英]python configparser to parse the data saved in a text file
我有一個名為sampl1.txt的文本文件。 這是此文本文件內的內容:
111
112
113
114
115
我有一個名為config_num.ini的.ini文件,其中包含:-
[num_group]
file = sample1.txt
這是代碼段:
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('config_num.ini')
sample = config.get('num_group','file')
print sample
有什么方法可以解析它,以便當我閱讀此“文件”並嘗試打印時,它會打印txt文件中的元素? 現在,它會打印sample1.txt。 我要打印數字。
您幾乎自己回答了這個問題!
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('config_num.ini')
sample = config.get('num_group','file')
sample = open(sample, 'r').read()
print sample
好吧,您必須重寫ConfigParser,但我建議您僅在調用get時加載文件
from ConfigParser import ConfigParser
class MyConfigParser(ConfigParser):
def get(self, section, option, **kwargs):
ret = super(MyConfigParser, self).get(section, option, **kwargs)
if option == "file":
try:
return open(ret, 'r').read()
except IOError:
pass
return ret
然后,您可以創建新的ConfigParser
cfg = MyConfigParser()
cfg.read('config_num.ini')
print cfg.get('num_group', 'file')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.