1

I need to first create an empty list, then insert one element and save it to the disk. Then again read the list from disk and append another element to the list and then again save the list to the disk and then again read the list and save another element for further operations and so on. My current code:

import pickle
emptyList = [] # create empty list
x = 'john' #this data is coming from client, so will change on each server call
emptyList.append(x) # append element
with open('createList.txt', 'wb') as f: # write to file
      pickle.dump(emptyList, f)
with open('createList.txt', 'rb') as f: # read from file
      my_list = pickle.load(f)
print my_list # print updated list

Now what I get is updated list like this:

#if x = 'john' then I get
['john']
#if x = 'george' then I get
['george']
#if x = 'mary' then I get
['mary']
# ..... and so on

What I want is to append the elements, like this:

['john','george','mary',....] 

1 Answer 1

1

just change

emptyList = [] # create empty list

to

emptyList = [] if not os.path.exists("createList.txt") else pickle.load(open("createList.txt"))

that way if your list already exists you will load it ... although then it is no longer an "emptyList"

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.