Hello there,

I am currently working on a indepedendent project and I am realtively new to Python. Please note that this question revolves around Python version 3. But if you have a answer in Python 2 just write it down and tell me it is in Python 2 thanks.

What I am trying to do is save a program from within so that when it is opened again it will have the stuff.

Example

Example = []

UserInputEx = input("Enter somethng here")
#In this case I would enter HappyCodingDude

#What ever command would be used here or someplace else to save it


Now Imgaine I open the program this is what I would like to see

 Example = ['HappyCodingDude']

    UserInputEx = input("Enter somethng here")
    #In this case I would enter HappyCodingDude

    #What ever command would be used here or someplace else to save it

Recommended Answers

All 2 Replies

Hmmn, tricky. While it is possible to do that, it is more dofficult that you probably expect, and almost certainly not what you actually want anyway.

I expect that the real goal here is to save the user's information - say, their name and a high score - so that it will automagically appear next time the program is run, right? Well, I suppose you could indeed use self-modifying code for it the way you propose, doing so is fraught with peril; you are all too likely to wreck the code that way, ending up with an unusable program or worse one that seems to work at first but has subtle bugs in it.

The more typical solution is to store the user information in a separate data file, which you could then check for at the start of the program and, if it is there, load the data from into the variables. You would do something like this:

from os.path import exists

dataFilePath = "foo.csv"

userInfo = dict()

if exists(dataFilePath):
    with open(dataFilePath, 'r') as infile:
        for data in infile.readlines():
            key, value = data.split(';')
            userInfo[key] = value

    for key in userInfo.keys():
        print('{0}: {1}'.format(key, userInfo[key]))

else:
    userInfo['name'] = input("Enter your name: ")
    userInfo['birth date'] =  input("Enter your data of birth (mm/dd/yyyy): ")
    userInfo['home city'] = input('Enter the city you live in: ')
    with open(dataFilePath, 'w') as outfile:
        for key in userInfo.keys():
            print('{0};{1}'.format(key, userInfo[key]), file=outfile)

THis is a simple example, but should do what you want.

Member Avatar for iamthwee

Like that or save to a db. Whichever floats your boat.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.