0

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?

6
  • Look up pickle. It allows you to easily save ('serialize') data of any Python type and later reimport those. Commented Mar 9, 2016 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 module works quite well for many purposes. Commented Mar 9, 2016 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. Commented Mar 9, 2016 at 23:08
  • @roadrunner66 pickle has security issues (see here) and I would not advice it unless I'm really sure what it's being used for. Commented Mar 9, 2016 at 23:09
  • 1
    You should refer to this to improve your question. That said, what you're actually looking for is a signal handler: stackoverflow.com/questions/1112343/… Commented Mar 10, 2016 at 0:24

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.