11

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!

dot.Py
5,1875 gold badges35 silver badges55 bronze badges
asked Apr 25, 2017 at 12:36
11
  • 3
    why use a text file as a database? Commented Apr 25, 2017 at 12:38
  • 3
    Read Pandas, you can use DataFrames Commented Apr 25, 2017 at 12:39
  • 1
    You should definitely take a look at sqlite3.. Commented Apr 25, 2017 at 12:39
  • 2
    If you want to use database logic based on a single file, have a look at sqlite. Commented Apr 25, 2017 at 12:40
  • 3
    You could use csv files. Basically, you comma separate values (or you could separate using |. Commented Apr 25, 2017 at 12:56

1 Answer 1

21

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')
    
Vini
8,46911 gold badges39 silver badges51 bronze badges
answered Dec 19, 2018 at 12:04
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.