0

I'm trying to convert a txt file to JSON using this:

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)

The error happens at the line:

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

And I'm wondering whether my use of the asterisk/star(*) operator is incorrect, or if I'm missing something else.

Edit: The input is an already sanitized TXT file, that follows this structure:

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

When printing the first element inside "n", this is the output:

['48655916', 'AGUILAR', 'FERNANDEZ', 'AMAZONAS',  'REGULAR']
Maddax
  • 3
  • 2
  • This is simply saying when you unpack the line with `*entry`, it does not contain a field for `UserType`. Is this missing in the file? – ChrisOram Aug 02 '21 at 09:13
  • Check if you have ```UserType``` present in every line of your file. – Ram Aug 02 '21 at 09:26
  • My bad, I should've included an excerpt of the input file as part of the original post. UserType **is** present in every line of the file – Maddax Aug 02 '21 at 22:29

1 Answers1

0

Since your input is CSV, would it not be simpler to use the csv module? It has a DictReader that seems like a good fit for the task.

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)
Tomalak
  • 332,285
  • 67
  • 532
  • 628