使用 namedtuple 将 txt 转换为 JSON 和 Python

Convert txt to JSON with Python using namedtuple

我正在尝试使用以下方法将 txt 文件转换为 JSON:

import json
import collections

def main():
    file = open("file.txt")
    #structure the output using namedtuple
    UserBase = collections.namedtuple(
        "UserBase",
        [
            "UserID",
            "UserName",
            "UserLastName",
            "UserLocation",
            "UserType",
        ],
    )
    #parse lines into a list
    n = [line.strip().split(',') for line in file.readlines()]
    #prepare list to output
    UserList = [UserBase(*entry) for entry in n]
    #output the conversion
    with open("database.json", "w") as output:
        json.dump([ob._asdict() for ob in UserList[:10]], output)

错误发生在行:

UserList = [UserBase(*entry) for entry in n]
TypeError: <lambda>() missing 1 required positional argument: 'UserType'

而且我想知道我对 asterisk/star(*) 运算符的使用是否不正确,或者我是否遗漏了其他内容。

编辑: 输入是一个已经清理过的 TXT 文件,其结构如下:

48655916,AGUILAR,FERNANDEZ,AMAZONAS,REGULAR
33783735,AGUILAR,LEONCIO,AMAZONAS,REGULAR
33407339,AGUILAR,ROJAS,AMAZONAS,REGULAR
48546141,ALFARO,CASTRO,AMAZONAS,REGULAR
...

打印 "n" 中的第一个元素时,输出如下:

['48655916', 'AGUILAR', 'FERNANDEZ', 'AMAZONAS',  'REGULAR']

既然你输入的是CSV,使用csv模块不是更简单吗?它有一个 DictReader 似乎很适合这项任务。

import csv
import json

csv_header = "UserID,UserName,UserLastName,UserLocation,UserType".split(",")

with open("file.txt", encoding='utf8', newline='') as file:
    users = csv.DictReader(file, delimiter=',', fieldnames=csv_header)
    
    with open("database.json", "w") as output:
        json.dump(list(users), output)