1

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Chris Aung
  • 9,152
  • 33
  • 82
  • 127

1 Answers1

6

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.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • what makes you prefer json over other options, for example, csv? – Jeff Tratner May 14 '13 at 03:55
  • Both are equally valid and have their uses. Json seems to be the new "in thing" in programming, and is particularly useful with nested structures and transferring such data, while CSVs are more rigid, with a table-like structure. – Snakes and Coffee May 14 '13 at 03:57
  • In general, flexibility (also, "csv" isn't really a single format but a vague description of a way of formatting tabular data; there are a ton of variants). In OP's case, "tabular data" might be a good fit, though. CSV is also supported by the standard library `csv` module, which can handle a fair number of standard variants IIRC. – Karl Knechtel May 14 '13 at 03:57
  • I never knew there was a word for this kind of thing. "Serialization" just made googling 20x easier for me. Thanks Karl +1'd – Senjai May 14 '13 at 03:58
  • There's also ["marshalling"](http://stackoverflow.com/questions/770474/what-is-the-difference-between-serialization-and-marshalling), which is worth understanding as a concept even though it doesn't seem to be relevant here. – Karl Knechtel May 14 '13 at 03:59