Saving user data in Python script

What is the preferred / normal way to store user input when running a Python script if I need data again the next time the script is run?

For example, my script performs calculations based on what the user enters, and then when the user runs the script again, it extracts the result from the last run.

Now I write the data to a text file and read it from there. I do not think that I will need to store very large records (less than 100, I would say).

I am targeting Windows and Linux users with both this script and a cross-platform solution. My only concern with using a text file is that I believe this may not be the best and usual way to do this.

So my question is: if you ever need to store some data for your script, how do you do it?

+4
source share
4 answers

You can use the slite database or CSV file. They are both very easy to operate, but lend themselves to lines of information of the same type.

A better option would be a shelve module

import shelve shelf = shelve.open(filename) shelf['key1'] = value1 shelf['key2'] = value2 shelf.close() # next run shelf.open(filename) value1 = shelf['key1'] #etc 
+9
source

For small amounts of data, Python pickle module is great for deleting data that you want easy access to later - just sort the data objects from memory and write to a (hidden) file in the user's home folder (good for Linux, etc.) or application data (on Windows).

Of, as @aaronnasterling mentioned, the sqlite3 file-based database is small, fast, and simple, which is not surprising that there are so many popular programs like Firefox and Pidgin.

+5
source

For 100 lines, plain text is fine using the standard ConfigParser or csv .

Assuming your data structure is simple, the text provides features (e.g. grep, vi, notepad) that exclude more complex formats.

+4
source

Since you only need the last result, just save the result,

eg

write ('something', wb)

it will save only the last result when you re-run the script, open and read the result

+1
source

All Articles