|

Is there a way to write to .txt all attributes of all objects stored in a list in Python in a specific format?

Question Description: I have a list in Python that stores objects with randomly assigned attributes, and I’m looking to print them in a specific format so that I can do some machine learning. The basic structure is like this:

import random

skills=['python', 'java', 'c++', 'c#']
student_names=['sam', 'tom', 'charlie']
people = []

class person:
    skills = []
    def __init__(self, skills, name):
        self.skills = []
        self.name=name[random.randint(0,(len(name))-1)]
        self.age=random.randint(20,30)
        for i in range(0,2):
            self.skills.append(skills[random.randint(0,(len(skills))-1)])

for i in range(0,3):
    people.append(person(skills, student_names))

I’d really like to write them to a .txt file so that it looks like this, for example:

sam,python c++,29

charlie,c# java, 22

tom, java python, 21

But every time I try to write to text or print to the console I get an output like this:

sam,[python, c++],29

charlie,[c#, java], 22

tom,[java, python], 21

Any ideas on how I can achieve the first output? Thanks very much, stack overflow community.

Expert Answer

The skills are saved in a list, so you want to convert them to a string before writing them out to a file. You can do that by joining the skills.

skills = " ".join(skills)

If I were writing this, the __init__() the method would take one name and a list of skills for a single person, and create a person object that represents that person. Then, have a separate function (maybe a class method) that takes a list of names and skills, randomly picks skills for each name, and creates a person object for each one. I’d also add a method that returns a comma-separated string like the one you want for each person.

class Person:
    def __init__(self, name, age, skills):
        self.skills = skills
        self.name=name
        self.age=age

    def to_csv(self):
        skills_str = ' '.join(self.skills) # Join the items in skills with a space before adding to the string
        return f"{self.name},{skills_str},{self.age}"

    @classmethod
    def create_persons(cls, names, skills):
        all_persons = []
        for name in names:
            p_skills = random.sample(skills, k=2)
            age = random.randint(20, 30)
            new_person = cls(name, age, p_skills)
            all_persons.append(new_person)
        return all_persons
    

To use this,

import random

skills=['python', 'java', 'c++', 'c#']
student_names=['sam', 'tom', 'charlie']
people = Person.create_persons(student_names, skills)

with open("out.txt", "w") as wf:
    for p in people:
        wf.write(p.to_csv() + "\n")

and this creates a file that looks like so:

sam,c++ c#,24
tom,java c#,20
charlie,c# c++,28

Similar Posts