Python Forum
namedtuples and text files - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: namedtuples and text files (/thread-22178.html)



namedtuples and text files - menator01 - Nov-02-2019

Is it possible to get the values out of a namedtuple that has been stored as a text file?

I am able to get the values out when the namedtuple is first made but, after storing it that approach fails.

Thanks for any help

some.txt file
HighScores(name='aname', score=850)
HighScores(name='anothername', score=230)
HighScores(name='yetanother', score=50)
This bit works when creating the file but, not after being stored in a text file
HighScores = namedtuple("HighScores", "name score")
name = HighScores(name, score)
print(getattr(name, "name"))



RE: namedtuples and text files - perfringo - Nov-02-2019

For me it is unclear what do you want to accomplish or what the exact problem is.


RE: namedtuples and text files - menator01 - Nov-02-2019

I'm storing the values in a text file keeping the namedtuple format for later sorting. The text file will be changing at various intervals.
I'm trying to pull the values out of each line of the files for display. Name and score. I was wondering if can get those values or if I need to take another approach at storing the data?

Thanks


RE: namedtuples and text files - perfringo - Nov-02-2019

I don't have context but it seems that rows of your sample some.txt file doesn't have any benefit being stored as namedtuple.

You can save data to file just as two comma separated values per row and read back into whatever datastructure (including namedtuple).

If there are more than one instance of namedtuple you should consider keeping them in some datastructure (list), otherwise access to them will be complicated.

This will enable you do:

>>> HighScores = namedtuple("HighScores", "name score")
>>> lst = [HighScores(name, score) for name, score in zip('first second third'.split(), '1 2 3'.split())]
>>> lst
[HighScores(name='first', score='1'), HighScores(name='second', score='2'), HighScores(name='third', score='3')]
>>> lst[0].name
'first'
>>> max(lst, key=lambda x: x.score).name    # name of the player with max score
'third'



RE: namedtuples and text files - menator01 - Nov-02-2019

Ok, thank you for the help