Chris Aung
Chris Aung

Reputation: 9492

Python proper way to store data

I am trying to store the names each with 5 attributes. For example:

name=apple 
attributes=[red,sweet,soft,fruit,healthy]

each names and attributes will be entered by the user. And there can be as many as hundreds of entries. Currently, the only way I know to store the values is to write it to a text file like this:

lines=[]
lines.append('{}|{}|{}|{}|{}|{} \n'.format(apple,red,sweet,soft,fruit,healthy))
myfile=open("test","a")
myfile.writelines(lines)
myfile.close()

So when I want to retrieve the value, I have to use split('|') command to individually split each lines like this:

for lines in open('test'):
    lines_splitted=lines.split('|')
if lines_splitted[0]=='apple':
    do something

Is there any better method to store the data other than what I did above? I want the attributes to be easily retrievable when I want just by calling the name of the item (e.g. apple) For your information, I am self taught and I only know python. So, I am looking for a way to do it only in python. No 3rd party or other languages.

Upvotes: 1

Views: 250

Answers (1)

Karl Knechtel
Karl Knechtel

Reputation: 61479

The general term you are looking for is serialization, which will help a lot for searching on SO or with Google.

Probably the easiest way to do it in Python, for normal cases, is to use the widely-recognized JSON format, which is supported by the standard library json module.

Upvotes: 6

Related Questions