Python:从文件

时间:2016-02-29 08:43:12

标签: python

在我的config.txt中,我有类似的东西。

# Server
server = localhost:8080

# Credentials
username = admin
password = password

# Some list here
important_info = [
    {
         id: 1,
         meaning: something
    },
    {
         id: 2,
         meaning: something else
    }
]

# Another list here
not_that_important_info = [
    {
         id: 3,
         meaning: another
    }
]

# And another one
some_other_info = [
    a,
    b,
    c,
]

我想读取文件,使得除了应被视为列表的行之外,每行都是列表的元素。到目前为止,我有这个。

def get_params_from_file():
    list = []
    with open('config.txt') as file:
        for line in file:
            if not line.lstrip().startswith('#'):
                # Do something so that it would treat some multiple lines a single line if it contains a list
                list.append(line.rstrip());

    return filter(None, list)

当然,它还没有按预期工作。有没有pythonic方法来做到这一点?

预期输出为:

['server = localhost:8080', 'username = admin', 'password = password', 'important_info = [{id: 1, meaning: something},{id: 2, meaning: something else}]', ... ] 

0 个答案:

没有答案