Changing option from st.selectbox does not saves the previous options data

I am new to stramlit. While creating app I have created a selected box. when option 1 from the selectbox is chosen then the multiselect box related select option saves the output to the text file. But when option 2 from the selectbox is chosen then the previously saved data in text file vanishes.

Module = st.selectbox("Select Module: ", ["",
                                          "Data1","Data2"],disabled =True)
if Module=="Data1":
    b_tests = st.multiselect( "Choose the B tests to run:",
        ["run_b" , "New"], )
    if(st.button('ADD TESTS')):
        test_b_list_t=b_tests
        data1[5]=' '.join(test_b_list_t)+'\n'
        with open('input.txt', 'w') as file:
            file.writelines(data1)
    st.write("You selected", len(b_tests), 'Tests')
if Module=="Data2":
    n_tests = st.multiselect("Choose the N tests to run",
        ["trigger_hh",  "power_test"], )
    if(st.button('ADD TESTS1')):
        test_n_list_t=n_tests
        data1[6]=' '.join(test_n_list_t)+'\n'
        with open('input.txt', 'w') as file:
            file.writelines(data1)
    st.write("You selected", len(n_tests), 'Tests')

You are overwriting your test lists test_b_list_t=b_tests.
You need to append instead: test_b_list_t.append(b_tests)

I’m taking a guess about the rest of your code, so apologies if I’ve misunderstood:

        with open('input.txt', 'w') as file:
            file.writelines(data1)

“w” mode is going to delete and recreate your file with whatever is in data1 on that particular rerun. If someone selects “Data1” on one script run which stores information in data1[5] and writes it to the file, then on another run when they select “Data2”, that information won’t be there. You’ll be writing data1 to your file where data1[5] doesn’t have information, but data1[6] does. I am guessing this might be what you’re referring to?

If you are wanting to build information from one rerun to the next, you will most likely want to use Session State. Is there some other reason for writing this information to a file, specifically? If not, try something like this to build complex selections from a user. I’ve used a dictionary to store information from different selectors for simplicity, but you can aggregate input in whatever format is convenient:

import streamlit as st

if "data" not in st.session_state:
    st.session_state.data = {}

category = st.selectbox("Category", ["A", "B", "C"])

if category=="A":
    a_select = st.multiselect("A tests", ["A1", "A2", "A3"])
    st.session_state.data["A"] = a_select
if category=="B":
    b_select = st.multiselect("B tests", ["B1", "B2", "B3"])
    st.session_state.data["B"] = b_select
if category=="C":
    c_select = st.multiselect("C tests", ["C1", "C2", "C3"])
    st.session_state.data["C"] = c_select

st.header("Current selections:")
st.session_state.data
1 Like

Hello @SiddhantSadangi

Thank you so much for your reply. Actually test_n_list_t=[] and
test_b_list_t=[] are the empty list, so I am assigning to new list name only. I am sharing a whole code in below comment there you can see the assignment for this list

Hello @mathcatsand
Thank you so much for your detailed reply. I am sharing the whole script and expected output as below,

SCRIPT

import streamlit as st
from pathlib import Path
import time,os,keyboard,psutil
st.set_page_config(layout='wide')
file_path = Path("input.txt")
with file_path.open('w') as file:
    file.write("Test_type\n")
    file.write("Interface\n")
    file.write("Slave ID\n")
    file.write("Baud Rate\n")
    file.write("COM\n")
    file.write(" \n")
    file.write(" \n")
file.close()

with open('input.txt', 'r') as file:
    data1 = file.readlines()

test_n_list_t=[ ]
test_b_list_t=[ ]
left, centre,right = st.columns(3,gap="large",vertical_alignment="top")
with left:
    Type = st.selectbox("Test Type: ", ["",
        "Test1",
        "Test2",
        "Test3"
])
    data1[0]=Type+"\n"
    with open('input.txt', 'w') as f:
        f.writelines(data1)

    Interface = st.selectbox("INTERFACE: ", ['','serial', 'tcp'])
    data1[1] = Interface + "\n"
    with open('input.txt', 'w') as f:
        f.writelines(data1)

    if Interface=='serial':
        sid = st.text_input("Slave ID",value=111)
        data1[2] = sid + "\n"
        with open('input.txt', 'w') as f:
            f.writelines(data1)
        if(st.button('Submit',key=1)):
            print(data1)

        brate = st.text_input("Baud Rate",value=9600)
        data1[3] = brate + "\n"
        with open('input.txt', 'w') as f:
            f.writelines(data1)
        if(st.button('Submit',key=2)):
            print(data1)

        cport = st.text_input("COM Port")
        data1[4] = "COM"+cport + "\n"
        with open('input.txt', 'w') as f:
            f.writelines(data1)
        if(st.button('Submit',key=3)):
            print(data1)

with centre:

    st.markdown("<h1 style='text-align: center; color: red;'>AUTOMATION</h1>", unsafe_allow_html=True)

    Module = st.selectbox("Select Module: ", ["",
                                              "Data1", "Data2"] )
    if Module == "Data1":
        b_tests = st.multiselect("Choose the B tests to run:",
                                 ["run_b", "New"], )
        if (st.button('ADD TESTS')):
            test_b_list_t = b_tests
            data1[5] = ' '.join(test_b_list_t) + '\n'
            with open('input.txt', 'w') as file:
                file.writelines(data1)
        st.write("You selected", len(b_tests), 'Tests')
    if Module == "Data2":
        n_tests = st.multiselect("Choose the N tests to run",
                                 ["trigger_hh", "power_test"], )
        if (st.button('ADD TESTS1')):
            test_n_list_t = n_tests
            data1[6] = ' '.join(test_n_list_t) + '\n'
            with open('input.txt', 'w') as file:
                file.writelines(data1)
        st.write("You selected", len(n_tests), 'Tests')

# with right:
#     level = st.slider("Select the level", 1, 5)
#     st.text('Selected: {}'.format(level))

REQUIRED OUTPUT IN TEXT FILE

Test2
serial
111
9600
COM3
run_b New
trigger_hh power_test

IN ACTUAL I AM GETTING AS BELOW

Test2
serial
111
9600
COM3

trigger_hh power_test

(Blank 6th line. I actual I want list 1 written as in REQUIRED OUTPUT IN TEXT FILE )
ACTION PERFORMED ON STREAMLIT SELECTION
Selecting the options from UI and store it in text file. All working good till I select Data1 option and its related multiselect( saving in text file)
Module = st.selectbox(“Select Module: “, [””,
“Data1”, “Data2”] )
But when I choose option 2 from the Select box (Data2) and try to its related multiselect options to text file I am getting as above (IN ACTUAL I AM GETTING AS BELOW)

I will try out the session state method and saving the output to the Dictionary. This might solve my problem.

1 Like