Sardor Abdirayimov
Sardor Abdirayimov

Reputation: 109

What magic command for appending code to existing file in jupyter notebooks

I am creating jupyter notebook tutorial to run streamlit app. I use %%writefile dashboard_ui.py to write the cell code into the given file.

%%writefile app.py
import streamlit as st

st.title('Hello Streamlit')
st.write('This is a simple Streamlit app running in Jupyter Notebook!')

Using the same magic command simply overwrite the code inside the file.

What magic command to use to insert the code into the file without overwriting old one?

I have tried to save code snippets in different files. Although, it is alternative solutions, there must be easier way to append on a single file.

Upvotes: 1

Views: 101

Answers (2)

Sardor Abdirayimov
Sardor Abdirayimov

Reputation: 109

I have figured it out! Flag -a!

%%writefile app.py
import streamlit as st

st.title('Hello Streamlit')
st.write('This is a simple Streamlit app running in Jupyter Notebook!')

Next time, I can use

%%writefile -a app.py  # flag -a -> indicate the insertion

with st.sidebar:
    st.title('South Korea Economic Dashboard')
    year_list = list(df.columns)[::-1]

Indeed, documentation has plenty things inside!

Upvotes: 0

Ahmed Alqershi
Ahmed Alqershi

Reputation: 21

Try adding -a to the magic command. to make it %%writefile -a app.py. This will force append rather than replace. If the file does not exist, it will create a new one with the specified name then append.

So you can start with

%%writefile app.py
import streamlit as st

st.title('Hello Streamlit')
st.write('This is a simple Streamlit app running in Jupyter Notebook!')

And then something like

%%writefile -a app.py
st.write('Bla Bla Bla')

Upvotes: 1

Related Questions