'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?



Solution 1:[1]

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.

Solution 2:[2]

You can just print as follows:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 FLAK-ZOSO
Solution 2