Files & the with statement
Use with open(...) to read or write files and close them automatically. Mode w overwrites a file; a appends. Always set encoding for text. Playground files live temporarily in the browser runtime.
हिन्दी में समझें
with open(...) फ़ाइल अपने आप बंद करता है। w पुरानी सामग्री मिटाकर लिखता है; a जोड़ता है। टेक्स्ट की encoding दें। यहाँ फ़ाइल ब्राउज़र में अस्थायी रहती है।
अभ्यास: notes.txt में I can code! लिखें, फिर पढ़कर प्रिंट करें।
Hinglish mein samjhein
with open(...) file ko automatically close karta hai. w overwrite karta hai aur a append. Text ke liye encoding do. Playground files browser runtime mein temporary hain.
Practice: notes.txt mein I can code! likho, phir read aur print karo.
A small Python example
with open("notes.txt", "w", encoding="utf-8") as file:
file.write("Learning Python!")
with open("notes.txt", encoding="utf-8") as file:
print(file.read())The browser playground runs real Python with Pyodide. Use sample variables instead of interactive input(). Browser package support differs from desktop Python.
Try this example in the Python playground →Practise this idea
Write I can code! to notes.txt, then read and print it.
Check answer & explanation
with open("notes.txt", "w", encoding="utf-8") as file:
file.write("I can code!")
with open("notes.txt", encoding="utf-8") as file:
print(file.read())Writing in mode w replaces the file contents. Reading the same temporary file returns the exact sentence you wrote.
Stuck in the course? Choose Check answer for either the challenge or quiz. Read the explanation and continue to the next lesson at your own pace.
Check your understanding
Which mode overwrites?
Check the quiz answer
w
w opens a file for writing and truncates existing content.
References & corrections
Use the official Python documentation for full language rules. Read how these lessons are made and checked. Found a mistake? Report it to Excel Keys with this lesson URL and a reproducible example.