File Handling
You will write, read, append, and loop through text files safely.
Open a file
A file lets your program keep text after it finishes. Use open() to access a file, then use with so Python closes it for you.
These examples use demo.txt in the current directory, which works in the browser sandbox.
| Mode | Meaning | Use |
|---|---|---|
| 'r' | Read an existing file | Read text |
| 'w' | Write and replace existing content | Create a fresh file |
| 'a' | Append to the end | Add another line |
| 'x' | Create a new file only | Avoid overwriting |
| 'r+' | Read and write | Update a file |
with open("demo.txt", "w") as file:
file.write('First line\nSecond line\n')
print('Saved demo.txt')
The 'w' mode creates the file if needed. If it already exists, its old contents are replaced. The with block closes the file when the indented code ends.
Read file contents
with open('demo.txt', 'w', encoding='utf-8') as file:
file.write('First line\nSecond line\n')
with open('demo.txt', 'r', encoding='utf-8') as file:
contents = file.read()
print(contents, end='')
read() returns the entire file as one string. Here end='' avoids adding an extra blank line because the file text already ends with a newline.
Reading lines from files
with open('demo.txt', 'w', encoding='utf-8') as file:
file.write('First line\nSecond line\nThird line\n')
with open('demo.txt', 'r', encoding='utf-8') as file:
first_line = file.readline().strip()
remaining_lines = file.readlines()
print(first_line)
for line in remaining_lines:
print(line.strip())
readline() gets one line. readlines() gets the remaining lines as a list. You can also loop directly over a file to handle one line at a time.
with open('demo.txt', 'w', encoding='utf-8') as file:
file.write('First line\nSecond line\n')
with open('demo.txt', 'a', encoding='utf-8') as file:
file.write('Third line\n')
with open('demo.txt', 'r', encoding='utf-8') as file:
for line in file:
print(line.rstrip())
Key points
- Use with open() so files close automatically.
- The w mode replaces old content.
- read() returns the entire file as one string.
- readline() and readlines() work with lines.
- Use a mode to control how you access a file.
Worked example
Keep a guest list on disk: write three names, close, then read them back.
with open("guests.txt", "w") as file:
file.write("Mim\nRafi\nJoe\n")
with open("guests.txt") as file:
print(file.read())
How it works, step by step
- "w" mode creates/truncates the file; write() adds text.
- with closes the file automatically, even on errors.
- Reading with no mode defaults to "r".
References & Further Reading
Related entries from PyLabs's own reference library.
Practice exercise
Not passed yetWrite Hello file! followed by a newline to demo.txt. Then read the file and print its contents without adding an extra newline.
# Write your code below
Check yourself
File Handling quiz
10 questions. You get instant feedback per question, and the timer starts when you press the button.
Lesson incomplete
Not completedCreate an ID or sign in to save lesson completion across devices.