0

i have written this code using this https://stackoverflow.com/a/48217112/14713550

i want to to append stockname to the file. whenver i print the data only one element is printed. all previous elements are vanished.

how to fix this?

    import pickle
    filename = 'blocklist2.pkl'
    data = []

    with open(filename, 'rb') as rfp:
        data = pickle.load(rfp)

    data.append(stock_name)

    with open(filename, 'wb') as wfp:
        pickle.dump(data, wfp)

    with open(filename, 'rb') as rfp:
        data = pickle.load(rfp)

    print(data)

update

used csv module instead of pickle

@app.route('/', methods=["GET", "POST"])
def home():
    if request.method == "POST":
        stockname = request.form.get("stockname")

        data = [stockname]
        lis = []
        lis.append(data)
        #append data
        file = open('blocklist.csv', 'a+', newline='')
        with file:
            write = csv.writer(file)
            write.writerows(lis)

        lis_to_render = []
        with open('blocklist.csv', 'r') as csv_file: 
            csv_reader = csv.reader(csv_file)
            for line in csv_reader:  
                lis_to_render.append(line[0])

        return render_template('index.html',lis = lis_to_render)       


    lis_to_render = []
    with open('blocklist.csv', 'r') as csv_file:
        csv_reader = csv.reader(csv_file)
        for line in csv_reader:
            lis_to_render.append(line[0])
user4599
  • 77
  • 3
  • 11
  • 1
    This might be worth looking at: https://stackoverflow.com/q/12761991/10006365 – nathanscain Apr 24 '21 at 04:13
  • @cainns98 i want to append string `stockname` to a list, so what should be 'p' here in this code with open(filename, 'a+') as fp: pickle.dump(p,fp) – user4599 Apr 24 '21 at 04:18
  • 1
    Okay, then (from what I know of pickle) this can only really be done without unpickling by adding each element to the pickle file 1 by 1 in ab mode. This let's you add at anytime and it can still be read in using EOF indicators (or list building if the length was known) The first part is shown here: https://stackoverflow.com/a/28078606 – nathanscain Apr 24 '21 at 04:42
  • 1
    Not sure why data is vanishing, but it might be that it's being saved as separate entries which have to be loaded one at a time. See this for an example of how to load till the file is empty: https://stackoverflow.com/a/3871442 – nathanscain Apr 24 '21 at 05:01
  • 1
    @cainns98 thanks for the help, i realized that same task can be done using csv also, i have updated the working code. – user4599 Apr 24 '21 at 05:44

0 Answers0