Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
69 views
in Technique[技术] by (71.8m points)

python - How to load a list, add an element to it and then store it again?

I'm using Python 3.8

I want to load a list of no integer value that is in a file ex: ["a", "b", "c"], no matter the kind of the file. Then I want to add to this list an element ex "d" so the final list would be ["a", "b", "c", "d"].

Next, this list will be written in the same file replacing what was inside. In this way a will have a clean file with the updated list.

This process will be repeated many times.

I thought it was a simple process and maybe it is, but I can't find a way.

question from:https://stackoverflow.com/questions/65860350/how-to-load-a-list-add-an-element-to-it-and-then-store-it-again

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Doing what you want is possible. But you shoul use instead le library pickle. First import picle

import pickle

For saving the variable you can use this

def saver(obj): #Pass the object you want to save
    pickle_file = open("data.pickle", "wb")
    pickle.dump(obj,pickle_file)
    pickle_file.close

Then to load :

def loader():

    pickle_file = pickle_file = open("data.pickle", "rb")
    data = pickle.load(pickle_file)
    pickle_file.close()
    return data

Exemple:

saver([1,2,3,4])
liste = loader()
print(liste)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...