import streamlit as st # Function to read file content def read_file(uploaded_file): try: # Read the file content content = uploaded_file.read().decode("utf-8") return content except Exception as e: st.error(f"Error reading file: {e}") return None # Function to write text to a file def write_to_file(content): try: with open("modified_file.txt", "w") as f: f.write(content) return "modified_file.txt" except Exception as e: st.error(f"Error writing to file: {e}") return None # Function to add text to the file def add_text_to_file(content, new_text): return content + "\n" + new_text # Streamlit UI st.title("File Handling Application") # File upload widget uploaded_file = st.file_uploader("Choose a file", type=["txt"]) if uploaded_file is not None: # Read the content of the uploaded file file_content = read_file(uploaded_file) if file_content: # Display the content of the file st.subheader("File Content") st.text_area("Content", file_content, height=200) # Option to add text to the file st.subheader("Add Text to File") new_text = st.text_area("Text to add", "", height=100) if st.button("Add Text"): if new_text: updated_content = add_text_to_file(file_content, new_text) st.success("Text added successfully!") # Display the updated file content st.subheader("Updated File Content") st.text_area("Updated Content", updated_content, height=200) # Allow user to download the updated file file_path = write_to_file(updated_content) if file_path: st.download_button( label="Download Updated File", data=open(file_path, "rb").read(), file_name="modified_file.txt", mime="text/plain" ) else: st.warning("Please enter some text to add to the file.")