在python中解析文件部分

时间:2013-07-04 13:21:06

标签: python python-2.7

我有一个文本(abc.txt)文件,在文本文件中包含以下条目:

[General]
Local=C:\Work\July\
path=C:\Work\July\abc

[Field1]
BB0B2BA8--EFE4-4567-B8AE-0204D4BF9F60=

[CustDetails]
BB0B2BA8-EFE4-4567-B8AE-0204D4BF9F60=NOthing

[DirName]
8e27822e-5f46-4f41=TEST

[URLNAME]
8e27822e-5f46=https://

[DestURL]
8e27822e-5f46=some_URL

我想解析abc.txt文件并接受变量。比如变量

MYpath = C:\Work\July\abc
custdetails= Nothing
dir_name = TEST
URL_Name = https://
DestURL = some_URL

谢谢,

2 个答案:

答案 0 :(得分:2)

使用ConfigParser:

import ConfigParser

config = ConfigParser.ConfigParser()
config.read('abc.txt')

dic = {}

for section in config.sections():
    for option in config.options(section):
        res = config.get(section, option)
        if res == '':
            continue
        dic.update({section: res})

print dic

输出:

{'DestURL': 'some_URL', 'URLNAME': 'https://', 'CustDetails': 'NOthing', 'DirName': 'TEST', 'General': 'C:\\Work\\July\\abc'}

答案 1 :(得分:0)

您可以在此处使用dict

>>> dic = {}
with open('abc.txt') as f:
    data = f.read()
    lines = data.split('\n\n')
    for line in lines:
        line = line.split('\n')
        field = line[0].strip('[]')
        val = line[-1].split('=')[1]
        if val:
            dic[field] = val
...             
>>> dic
{'DestURL': 'some_URL',
 'URLNAME': 'https://',
 'CustDetails': 'NOthing',
 'DirName': 'TEST',
 'General': 'C:\\Work\\July\\abc'}