File size: 2,185 Bytes
3349d94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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.")