Home > Software design >  Taking text file input as list of class item elements
Taking text file input as list of class item elements

Time:04-21

I have a class threeItems defined as

class threeItems:
    def __init__(self, a=0, b=0, c=0):
        self.a = a
        self.b = b
        self.c = c

I want to feed input from a text file as a series of threeItems objects, each instance object separated by a space character and each threeItems object to be separated by a newline character. For example,

0 3 2
4 5 8

becomes a threeItems list of length n=2 called out with out[0].a = 0, out[0].b = 3, out[0].c = 2, and out[1].a = 4, out[1].b = 5, and out[1].c = 8. I think it should be something like

x, y, z = [int(x) for x in input().split()] for _ in range(n)]

but I'm not sure how to then append these triples as elements to out. I am still somewhat of a novice at Python, so this may be obvious, but I can't find any answers to this elsewhere.

CodePudding user response:

You can use .append() along with a call to the threeItems constructor:

result = []
with open('in.txt') as file:
    for line in file:
        x, y, z = [int(item) for item in line.rstrip().split()]
        result.append(threeItems(x, y, z))

for item in result:
    print(item.a, item.b, item.c)

This outputs:

0 3 2
4 5 8

CodePudding user response:

You can try using pandas to read a file:

import pandas as pd

df = pd.read_csv("items.txt", delimiter=" ", header=None, names=["a", "b", "c"])
items = [threeItems(**item) for item in df.to_dict("records")]

print(f"{items[1].a=}")
for item in items:
    print(f"{item.a=}, {item.b=}, {item.c=}")

outputs:

items[1].a=4
item.a=0, item.b=3, item.c=2
item.a=4, item.b=5, item.c=8
  • Related