Friendly introduction
Have you ever written something in a notebook to save it for later? Files are like Python's notebooks. They let your programs remember things even after the code stops running. Today you'll learn how to make a file, write to it, read from it, and add more to it. It's easier than you think!
What you'll learn
- How to open a file the safe way
- How to write text to a file
- How to read text from a file
- How to add (append) new text to an existing file
- Where your file gets saved
Important idea: the with block
We'll use with open(...) as file: because it automatically closes the file for us. This keeps things neat and prevents mistakes.
Step 1: Write (create) a file
Mode 'w' means "write." It creates a new file or overwrites an existing one.
Python example:
# Create a new text file and write some lines
with open('greeting.txt', 'w') as f:
f.write('Hello, PyVerse!\n')
f.write('Files are just text.\n')
f.write('This is line 3.\n')
print('Done writing greeting.txt')Notes:
- '\n' makes a new line.
- If greeting.txt already exists, 'w' will replace its contents.
Step 2: Read the whole file
Mode 'r' means "read." Use read() to get everything as one string.
with open('greeting.txt', 'r') as f:
content = f.read()
print('--- File contents ---')
print(content)Step 3: Append (add) more text
Mode 'a' means "append." It adds new text to the end of the file without erasing what's already there.
with open('greeting.txt', 'a') as f:
f.write('Adding a new line at the end.\n')
print('Appended a line!')Step 4: Read a file line by line
This is handy when you want to process each line separately.
with open('greeting.txt', 'r') as f:
for line in f:
print(line.strip()) # .strip() removes the ending newlineStep 5: Where is my file saved?
- If you use just a name like 'greeting.txt', it saves in the same folder as your Python file (or where you run the program).
- You can also give a path, like 'C:/Users/You/Documents/greeting.txt' on Windows or '/Users/you/Documents/greeting.txt' on macOS.
Quick tips and common mistakes
- Forgetting '\n' means your lines might stick together.
- If you try to read a file that doesn't exist, Python raises FileNotFoundError. First create it (write) or check the file name.
- Always prefer with open(...) so the file closes automatically.
Mini exercise: Favorites list
Goal: Ask the user for three favorite snacks, save them to a file, then read and print them.
Instructions:
- Ask the user three times for a snack.
- Write each snack on its own line in a file called favorites.txt.
- Open the file again and print the lines back to the user.
Try it yourself:
# 1) Collect favorites
snacks = []
for i in range(3):
snack = input(f'Enter favorite snack #{i+1}: ')
snacks.append(snack)
# 2) Write them to a file (one per line)
with open('favorites.txt', 'w') as f:
for s in snacks:
f.write(s + '\n')
# 3) Read them back and print
print('\nYou entered:')
with open('favorites.txt', 'r') as f:
for line in f:
print('- ' + line.strip())Short summary
- Use with open('name.txt', 'w') to create or overwrite a file and write text.
- Use with open('name.txt', 'r') to read a file (read() or loop line by line).
- Use with open('name.txt', 'a') to add new text at the end of a file.
- '\n' makes a new line, and .strip() removes it when printing.
- Files are saved in your current folder unless you give a full path.
You now know how to make your programs "remember" things with files. Great job!