0

我有一个文本(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

谢谢,

4

2 回答 2

2

使用配置解析器:

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'}
于 2013-07-04T15:02:26.923 回答
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'}
于 2013-07-04T13:32:57.990 回答