【问题标题】:parse the file and generate a list of dictionaries where each user information is represented by a single dictionary解析文件并生成一个字典列表,其中每个用户信息都由一个字典表示
【发布时间】:2021-07-30 05:32:06
【问题描述】:

我有一个类似image for txt file 的.txt 文件,其中每一列都可以归类为UserName:ReferenceToThePassowrd:UserID:GroupID:UserIDInfo:HomeDir:LoginShell。 我想制作一个脚本来解析文件并生成一个字典列表,其中每个用户信息都由一个字典表示:

以下是最终输出的示例:

[
    {
        "user_name": "user1",
        "user_id": "1001",
        "home_dir": "/home/user1",
        "login_shell": "/bin/bash"
    },
    {
        "user_name": "user2",
        "user_id": "1002",
        "home_dir": "/home/user2",
        "login_shell": "/bin/bash"
    }
]

【问题讨论】:

标签: python python-3.x python-2.7 python-requests


【解决方案1】:

执行此操作的一个非常基本的方法可能如下所示:

objects = []
for line in open("myData.txt"):
    line = line.strip()
    items = line.split(":")

    someDict = {}
    someDict["first"] = items[0]
    someDict["second"] = items[1]
    # ... etc
    objects.append(someDict)

print(objects)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-11
    • 2023-01-29
    • 1970-01-01
    • 2016-11-09
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 2021-07-14
    相关资源
    最近更新 更多