بتل کد Battle Codeدارد باز می‌شود…

جواب «Read It Back» چالش 4 از جلسه‌ی 17

سؤال

تابع read_note را بنویس (دکمه‌ی Read file): فایل note.txt را بخواند و متنش را در متن shown بگذارد. اگر فایل هنوز نبود، پیام No file yet بدهد، بدون خطای قرمز.

راهنما

try: و زیرش with open("note.txt", encoding="utf-8") as f: و shown.value = f.read(). بعد except FileNotFoundError: با پیام.

یک جواب درست

import app

def write_note():
    with open("note.txt", "w", encoding="utf-8") as f:
        f.write(box.value)
    app.toast("Saved to note.txt")

def read_note():
    try:
        with open("note.txt", encoding="utf-8") as f:
            shown.value = f.read()
    except FileNotFoundError:
        app.toast("No file yet")

app.title("Notes")
box = app.input("Note")
app.button("Write file", write_note)
app.button("Read file", read_note)
shown = app.text("")
app.run()

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن