0
RandomList = []

def endless():

    x = input("x: ")
    RandomList.append(x)
    print(RandomList)

endless()

I want to make a list where Input() gets appended to RandomList, and the numbers gets to stay there for ever even if I close the file. I don't really know whether it can be done or not. Thank you.

jpp
  • 159,742
  • 34
  • 281
  • 339
Smanke
  • 3
  • 1
  • 3
  • 1
    https://docs.python.org/3/library/persistence.html – cs95 Feb 11 '18 at 13:20
  • Possible duplicate of [Python Storing Data](https://stackoverflow.com/questions/27913261/python-storing-data) – jpp Feb 11 '18 at 13:41
  • You should add some loop to make input and store process truly endless. In each loop you need to add code to save the list to a file. Search for "loops in python" and "saving to file in python". – rnso Feb 11 '18 at 13:43

1 Answers1

0

So to make objects persistent, one module you could use would be the pickle module.

One example would be:

import pickle

RandomList = []

with open('randomlist_persistence', 'wb') as outp:
    pickle.dump(RandomList, outp)

This would save the RandomList list object to a file. To then access it again, you can use:

with open('randomlist_persistence', 'rb') as inp:
    RandomList = pickle.load(inp)

Bear in mind, opening the file in write-mode will overwrite the list, so if you want to ammend a list, ensure you open the file in read mode first, save the list to a variable and then open it again it write-mode and re-write it.

I.e.

with open('randomlist_persistence', 'rb') as inp:
    RandomList = pickle.load(inp)

...... do any modifications here ......

with open('randomlist_persistence', 'wb') as outp:
    pickle.dump(RandomList, outp)

Hopefully this helps. More information on the pickle module can be found here: https://docs.python.org/3/library/pickle.html?highlight=pickle#module-pickle