I want to know what is the efficient way to insert several data to text file as database logic?
For instance I have set of cars, these cars have their id, name, and color variable.
id | name | color
1 | car1 | green
2 | car2 | red
3 | car3 | blue
I want to insert the data above to text file using python.
Later on I want to search a car, for instance based on its color.
Which method should I follow? An example with an explanation will really be appreciated!
1 Answer 1
In this simple case I would definitely recommend you to use tinyDB:
- it's really tiny
- written in pure Python
- works with Python 2.7 and 3.6 as well
- you can easily extend it
- fast installation with pip:
pip install tinydb
It's definitely not for advance purposes (managing relationships or having ACID), but very flexible text file based storage, really easy to use. Check the link above.
For your case you can do something like this:
from tinydb import TinyDB
db = TinyDB('path_to_your_db_folder/db.json')
db.insert({'id': 1, 'name': 'car1', 'color': 'green'})
db.insert({'id': 2, 'name': 'car2', 'color': 'red'})
db.insert({'id': 3, 'name': 'car3', 'color': 'blue'})
You see, it's simple Python dict.
Querying is also simple:
- get all with
db.all() query your data:
from tinydb import Query Cars = Query() db.search(Cars.color == 'green')
Pandas, you can useDataFrames|.