S12312
S12312

Reputation: 45

Write the attributes of an object into a txt file

So i am trying to write to a text file with all the attributes of an object called item.

I was able to access the information with:

>>>print(*vars(item).values()])
125001 John Smith 12 First Road London N1 55 74

but when i try write it into the text file:

with open('new_student_data.txt', 'w') as f:
    f.writelines(*vars(item).values())

it throws an error as writelines() only takes one argument.

how can i write all the attributes of item to a single line in the text file?

Upvotes: 0

Views: 1229

Answers (3)

Every class is capable of outputting a dictionary by calling __dict__ method. This way you are getting the attribute name and the value as a dictionary, then you could simply iterate through it and write it to a txt file:

with open('params.txt'), 'w') as f:
    for param, value in params.__dict__.items():
        if not param.startswith("__"):
            f.write(f"{param}:{value}\n")

Here I am also getting rid of default class attributes that start with "__". Hope this helps

Upvotes: 1

Adon Bilivit
Adon Bilivit

Reputation: 27071

You can just print as follows:

with open('new_student_data.txt', 'w') as f:
  print(*vars(item).values(), file=f)

Upvotes: 1

FLAK-ZOSO
FLAK-ZOSO

Reputation: 4102

with open('new_student_data.txt', 'w') as f:
    for i in vars(item).values():
        f.write(f"{i}\n")

If file.writelines only takes an iterable and doesn't support *args, you can always iterate over your list and write it with file.write.

Upvotes: 1

Related Questions