我在一个文件中有一些数据如下所示:
[General]
StartWithLastProfile=1
[Profile0]
Name=Sveta
IsRelative=1
Path=Profiles/lqtrtj3x.Sveta
Default=1
[Profile1]
Name=Jason
IsRelative=1
Path=Profiles/er5rtak4.Jason
[Profile2]
Name=Sarah
IsRelative=1
Path=Profiles/23mvfqcj.Sarah
我想读取所有数据并基于这些数据构建一个namedtuple
,但是输出非常奇怪,我不知道如何解释它以及如何处理它
以下是我所厌倦的:
def split_and_return_data(data_to_split):
return data_to_split.split("=")[1]
def main():
# read_profile_attributes returns a list containing the data
profile_attributes = read_profile_attributes(profile_ini)
# Ignore the first 3 elements
list_of_firefox_profiles = list_of_profile_attributes[3:len(profile_attributes)]
firefox_profile = namedtuple("Profile", ["Name", "IsRelative", "Path", "Default"])
name = None
isRelative = None
path = None
default = None
for profile_attribute in list_of_firefox_profiles:
if profile_attribute and "Name" in profile_attribute:
name = split_and_return_data(profile_attribute)
elif profile_attribute and "IsRelative" in profile_attribute:
isRelative = split_and_return_data(profile_attribute)
elif profile_attribute and "Path" in profile_attribute:
path = split_and_return_data(profile_attribute)
elif profile_attribute and "Default" in profile_attribute:
default = split_and_return_data(profile_attribute)
print("{0}, {1}, {2}, {3}".format(name, isRelative, path, default))
if __name__ == "__main__":
main()
输出:
None, None, None, None
Sveta, None, None, None
Sveta, 1, None, None
Sveta, 1, Profiles/lqtrtj3x.Sveta, None
Sveta, 1, Profiles/lqtrtj3x.Sveta, 1
Sveta, 1, Profiles/lqtrtj3x.Sveta, 1
Sveta, 1, Profiles/lqtrtj3x.Sveta, 1
Jason, 1, Profiles/lqtrtj3x.Sveta, 1
Jason, 1, Profiles/lqtrtj3x.Sveta, 1
Jason, 1, Profiles/er5rtak4.Jason, 1
Jason, 1, Profiles/er5rtak4.Jason, 1
Jason, 1, Profiles/er5rtak4.Jason, 1
Sarah, 1, Profiles/er5rtak4.Jason, 1
Sarah, 1, Profiles/er5rtak4.Jason, 1
Sarah, 1, Profiles/23mvfqcj.Sarah, 1
Sarah, 1, Profiles/23mvfqcj.Sarah, 1
我想取Name
、IsRelative
、Path
和Default
(None
如果Default
不存在)并创建一个namedtuple
。我知道我正在打印示例中的结果,但是如果我创建了namedtuple
并将其存储在list
中,它将创建一个namedtuple
,其中包含输出中看到的所有数据。只有3namedtuples
存储在list
中
有一个名为configparser的库
这可能比你正在尝试的要容易
https://docs.python.org/3.6/library/configparser.html
相关问题 更多 >
编程相关推荐