I am writing a program in Python where a user can input information that is saved - even if the program is terminated. How do I implement this?
Asked
Active
Viewed 2,475 times
0
-
Look up `pickle`. It allows you to easily save ('serialize') data of any Python type and later reimport those. – roadrunner66 Mar 09 '16 at 23:06
-
Yup, this is possible :-) You should probably [edit] your question to include your code; that way more specific advice can be given. In general, though, I would say using the [`json`](https://docs.python.org/3/library/json.html) module works quite well for many purposes. – Martin Tournoij Mar 09 '16 at 23:07
-
You can write it to a file, use a database etc etc. There are literally tons of storage options. Just search, pick one and go ahead. – Hossain Muctadir Mar 09 '16 at 23:08
-
@roadrunner66 `pickle` has security issues ([see here](http://stackoverflow.com/a/26934565/660921)) and I would not advice it unless I'm really sure what it's being used for. – Martin Tournoij Mar 09 '16 at 23:09
-
1You should [refer to this](http://www.stackoverflow.com/help/mcve) to improve your question. That said, what you're actually looking for is a signal handler: http://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python – Nathaniel Ford Mar 10 '16 at 00:24
-
To summarize the other answers, in order to save information, look at any modules from the "Data persistence" (the name speaks for itself) in the python documentation https://docs.python.org/2/library/persistence.html. – Sci Prog Mar 10 '16 at 00:58
1 Answers
1
Assuming you want the user to input a string of data, you can use raw_input()
to get it, and then send it to a file using pickle
library, as mentioned in comments above.
To use pickle
, you should before open
a file in writing mode and then use this file to dump into it your object containing the string.
A secure way to open a file is to use a with
statement, it will be closed at the end of the statement.
import pickle
myData = raw_input('What is your name ? ')
with open("name.p", "wb" ) as myFile:
pickle.dump(myData, myFile)
Later, you can get back the object by opening the pickle file in read mode and store its content in a variable.
import pickle
with open("name.p", "rb" ) as myFile:
myData = pickle.load(myFile)

Pierre Cordier
- 494
- 3
- 17