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!
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.
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.
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.
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.
In this simple case I would definitely recommend you to use tinyDB:
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:
db.all()
query your data:
from tinydb import Query
Cars = Query()
db.search(Cars.color == 'green')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With