Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a text file as database in Python?

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!

like image 300
Lunatic Fnatic Avatar asked Apr 25 '17 12:04

Lunatic Fnatic


People also ask

Can you use a TXT file as a database?

Yes you can use a . txt file as a database but you should make it a lot easier on yourself in the long run and learn mySQL in a couple of hours so you are doing it more along the lines of industry standards.

How does Python store data in a text file?

To write to a text file in Python, you follow these steps: First, open the text file for writing (or append) using the open() function. Second, write to the text file using the write() or writelines() method. Third, close the file using the close() method.

How do you use text files in Python?

To read a text file in Python, you follow these steps: First, open a text file for reading by using the open() function. Second, read text from the text file using the file read() , readline() , or readlines() method of the file object. Third, close the file using the file close() method.

Can I use Python to make a database?

Introduction. SQLAlchemy is a Python library for implementing SQL databases without using the SQL language itself. In other words, all you need to do is to implement your database using the Python language.


1 Answers

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')
    
like image 99
Nerxis Avatar answered Sep 22 '22 08:09

Nerxis