Back to Python Mastery
IntermediateTeenagers

File I/O

Your programs can read from and write to files on your computer. This is called File Input/Output (I/O).

To work with a file, you first need to open it. The with open(...) as ...: syntax is the recommended way, as it handles closing the file for you automatically.

**Writing to a file:**
Use the mode 'w' to write to a file. This will overwrite the file if it already exists.

with open("greeting.txt", "w") as f:
f.write("Hello, from Python!")

**Reading from a file:**
Use the mode 'r' to read a file.

with open("greeting.txt", "r") as f:
content = f.read()
print(content) # Will print "Hello, from Python!"

**Appending to a file:**
Use the mode 'a' to add to the end of an existing file without deleting its contents.

with open("greeting.txt", "a") as f:
f.write("\nHave a nice day!")

Working with files allows your programs to save data permanently.

Write to a File

Write a program that asks for a user's favorite color and saves it to a file named `favorite_color.txt`. This cannot be auto-graded.