-2

I'm still learning python and am currently developing an API (artificial personal assistant e.g. Siri or Cortana). I was wondering if there was a way to update code by input. For example, if I had a list- would it be possible to PERMANENTLY add a new item even after the program has finished running.

I read that you would have to use SQLite, is that true? And are there any other ways?

J Nowak
  • 17
  • 1
  • 1
    This is an XY problem. You do not want to change code, you are looking for a way to persist data between running the program. – tobias_k Aug 09 '16 at 08:13

2 Answers2

1

Hello J Nowak

I think what you want to do is save the input data to a file (Eg. txt file). You can view the link below which will show you how to read and write to a text file.

How to read and write to text file in Python

0

There are planty of methods how you can make your data persistent. It depends on the task, on the environment etc. Just a couple examples:

  • Files (JSON, DBM, Pickle)
  • NoSQL Databases (Redis, MongoDB, etc.)
  • SQL Databases (both serverless and client server: sqlite, MySQL, PostgreSQL etc.)

The most simple/basic approach is to use files. There are even modules that allow to do it transparently. You just work with your data as always.

See shelve for example.

From the documentation:

A “shelf” is a persistent, dictionary-like object. The difference with “dbm” databases is that the values (not the keys!) in a shelf can be essentially arbitrary Python objects — anything that the pickle module can handle. This includes most class instances, recursive data types, and objects containing lots of shared sub-objects. The keys are ordinary strings.

Example of usage:

import shelve

s = shelve.open('test_shelf.db')
try:
    s['key1'] = { 'int': 10, 'float':9.5, 'string':'Sample data' }
finally:
    s.close()

You work with s just normally, as it were just a normal dictionary. And it is automatically saved on disk (in file test_shelf.db in this case).

In this case your dictionary is persistent and will not lose its values after the program restart.

More on it:

Another option is to use pickle, which gives you persistence also, but not magically: you will need read and write data on your own.

Comparison between shelve and pickle:

Community
  • 1
  • 1
Igor Chubin
  • 61,765
  • 13
  • 122
  • 144