| 1 | age: 30 |
| 2 | is_active: true |
| 3 | name: John Doe |
| 4 |
edit_yaml_data.py
· 874 B · Python
Eredeti
import streamlit as st
import yaml
import pandas as pd
from io import StringIO
# 定義讀取 YAML 文件的函數
def read_yaml(file_path):
with open(file_path, 'r') as file:
return yaml.safe_load(file)
# 定義寫入 YAML 文件的函數
def write_yaml(file_path, data):
with open(file_path, 'w') as file:
yaml.dump(data, file, default_flow_style=False)
# 讀取 YAML 文件
file_path = 'data.yml'
data = read_yaml(file_path)
# 將 YAML 資料轉換為 DataFrame
data_df = pd.DataFrame([data])
# 使用 st.data_editor 編輯資料
edited_data_df = st.data_editor(data_df)
# 如果資料有變更,更新 YAML 文件
if st.button('Save'):
edited_data = edited_data_df.iloc[0].to_dict()
write_yaml(file_path, edited_data)
st.success('Data saved successfully!')
# 顯示編輯後的資料
st.write('Edited Data:', edited_data_df)
| 1 | import streamlit as st |
| 2 | import yaml |
| 3 | import pandas as pd |
| 4 | from io import StringIO |
| 5 | |
| 6 | # 定義讀取 YAML 文件的函數 |
| 7 | def read_yaml(file_path): |
| 8 | with open(file_path, 'r') as file: |
| 9 | return yaml.safe_load(file) |
| 10 | |
| 11 | # 定義寫入 YAML 文件的函數 |
| 12 | def write_yaml(file_path, data): |
| 13 | with open(file_path, 'w') as file: |
| 14 | yaml.dump(data, file, default_flow_style=False) |
| 15 | |
| 16 | # 讀取 YAML 文件 |
| 17 | file_path = 'data.yml' |
| 18 | data = read_yaml(file_path) |
| 19 | |
| 20 | # 將 YAML 資料轉換為 DataFrame |
| 21 | data_df = pd.DataFrame([data]) |
| 22 | |
| 23 | # 使用 st.data_editor 編輯資料 |
| 24 | edited_data_df = st.data_editor(data_df) |
| 25 | |
| 26 | # 如果資料有變更,更新 YAML 文件 |
| 27 | if st.button('Save'): |
| 28 | edited_data = edited_data_df.iloc[0].to_dict() |
| 29 | write_yaml(file_path, edited_data) |
| 30 | st.success('Data saved successfully!') |
| 31 | |
| 32 | # 顯示編輯後的資料 |
| 33 | st.write('Edited Data:', edited_data_df) |
| 34 | |
| 35 |