Python File Handling
1Python File Handling: overview
File handling means using open() to connect your program to a file, reading text from it or writing text into it, and then closing it so the work is saved.
Before this lesson: Python Strings, Python for Loops, Python Exceptions: try, except, else and finally
2Python File Handling: diagram
3Python File Handling: explained step by step
Variables disappear when a program stops. Files let you keep data — notes, settings, scores — and read it back later. Python's built-in open() function gives you a file object that you can write text into or read text out of.
Open files with with
The safest way to open a file is in a with block. When the indented block ends, Python closes the file for you, even if an error happens halfway through. Closing matters: written text can sit in a memory buffer and only reach the file when it is closed.
with open("todo.txt", "w") as f:
f.write("Buy milk\n")
f.write("Call Sam\n")
with open("todo.txt") as f:
print(f.read())write() never adds a line break, so end each line with \n yourself.
Choose the right mode
The second argument of open() is the mode:
"r"— read. This is the default, and the file must already exist."w"— write. Creates the file, or wipes it empty if it already exists."a"— append. Adds to the end and keeps what is already there.
Opening with "w" when you meant "a" is the classic way to lose data, so pick the mode on purpose.
Read line by line
You can loop over a file object: each pass gives you one line, including its \n. Use .strip() to remove it. f.readlines() gives you all lines as a list, and f.read() gives you the whole file as one string.
with open("scores.txt", "w") as f:
f.write("Asha,82\nBen,67\n")
with open("scores.txt", "a") as f:
f.write("Chen,91\n")
with open("scores.txt") as f:
for line in f:
name, score = line.strip().split(",")
print(name, "scored", int(score))Everything you read from a text file is a string. Convert it with int() or float() before doing maths.
When the file is missing
Reading a file that does not exist raises FileNotFoundError. If a missing file is a normal situation — say, the first time your program runs — catch it with try/except and fall back to a default.
Files in your browser
The code on this site runs inside your browser, which has its own temporary, in-memory file system. It starts empty, cannot see the files on your computer, and is cleared when you reload the page. That is why every example here writes a file before reading it. On your own computer, exactly the same code reads and writes real files in the current folder.
Quick reference: Python File Handling
- Python File Handling Cheat Sheet: open, read, write, CSV, JSON — Open files with `with open(path, mode, encoding="utf-8") as f:` so they close automatically, read with `read(…
- How to Read a File Line by Line in Python — Open the file with `with open("file.txt") as f:` and loop over it: `for line in f:`. Each `line` is one line …
- How to Write to a File in Python — Use `with open("notes.txt", "w", encoding="utf-8") as f:` then `f.write("text\n")`. Mode `"w"` replaces the f…
- How to Read a CSV File in Python — Use the `csv` module: `with open("data.csv", newline="", encoding="utf-8") as f:` then `csv.DictReader(f)` gi…
- How to Read a JSON File in Python — Open the file and call `json.load()`: `with open("data.json", encoding="utf-8") as f: data = json.load(f)`. Y…
- How to Check if a File Exists in Python — Use `pathlib`: `Path("data.txt").is_file()` is `True` only if the path exists and is a regular file. `Path(..…
- How to Convert JSON to a Dictionary in Python — Use `json.loads(text)` to turn a JSON string into a dictionary, or `json.load(file)` to read it from an open …
- Python String rstrip() Method — `text.rstrip(chars=None)` returns a new string with **trailing** (right-hand) whitespace, or any characters i…
4Python File Handling: syntax
with open("file.txt", "w") as f: # "w" write (overwrite), "a" append
f.write("some text\n") # strings only; add \n yourself
with open("file.txt") as f: # "r" (read) is the default mode
text = f.read() # whole file as one string
# lines = f.readlines() # list of lines
# for line in f: ... # one line at a time
5Python File Handling: run the example
Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.
entries = ["Mon: 5 km run", "Wed: 30 min swim", "Fri: 8 km run"]
with open("workouts.txt", "w") as f:
for entry in entries:
f.write(entry + "\n")
with open("workouts.txt", "a") as f:
f.write("Sun: yoga\n")
with open("workouts.txt") as f:
lines = f.readlines()
print("File closed:", f.closed)
print("Lines in file:", len(lines))
for number, line in enumerate(lines, start=1):
print(number, line.strip())Expected outputFile closed: True
Lines in file: 4
1 Mon: 5 km run
2 Wed: 30 min swim
3 Fri: 8 km run
4 Sun: yoga
7Python File Handling: how the example works
Hover or tap a step to highlight its lines in the example above.
- Line 1A list of three workout notes is created. This is the data we want to save.
- Line 3
open("workouts.txt", "w")creates the file (or empties it if it already exists) and names the file objectf. - Line 4-5Each entry is written with
"\n"added, becausewrite()does not start a new line by itself. - Line 7-8Mode
"a"keeps the three existing lines and adds"Sun: yoga"at the end. - Line 10-11With no mode given, the file opens for reading.
readlines()returns a list of 4 strings, each still ending in"\n". - Line 13We are outside the
withblock now, sof.closedisTrue— Python closed the file automatically. - Line 14
len(lines)counts the lines that came back from the file: 4. - Line 15-16
enumerate(..., start=1)numbers the lines from 1, andstrip()removes the trailing newline soprint()does not add blank lines.
8Python File Handling: common mistakes
Reading a file that was never created
✗ Wrong
with open("diary.txt") as f:
print(f.read())✓ Right
try:
with open("diary.txt") as f:
print(f.read())
except FileNotFoundError:
print("No diary yet - creating one.")
with open("diary.txt", "w") as f:
f.write("Day 1\n")Mode "r" needs an existing file. Write the file first, or catch FileNotFoundError when a missing file is expected. Remember that the browser's file system starts empty.
Using "w" when you meant "a"
✗ Wrong
with open("log.txt", "w") as f:
f.write("first visit\n")
with open("log.txt", "w") as f:
f.write("second visit\n")
with open("log.txt") as f:
print(f.read())✓ Right
with open("log.txt", "w") as f:
f.write("first visit\n")
with open("log.txt", "a") as f:
f.write("second visit\n")
with open("log.txt") as f:
print(f.read())Mode "w" empties the file every time it is opened. Use "a" to add to the end of an existing file.
Passing a number to write()
✗ Wrong
score = 95
with open("best.txt", "w") as f:
f.write(score)✓ Right
score = 95
with open("best.txt", "w") as f:
f.write(f"{score}\n")Text files store strings only. Convert the value with str() or an f-string, and add the newline yourself.
9Python File Handling: exercises
Write your answer, then press Check. The checks run in your browser.
1. Save a list to a file
Write code Easy ✓ CompletedComplete the function save_lines(filename, lines) so that it writes every string in lines to the file, one per line (each followed by \n). If the file already exists, its old contents should be replaced.
def save_lines(filename, lines):
# open the file in write mode and write each line followed by "\n"
pass
save_lines("shopping.txt", ["eggs", "rice", "apples"])
with open(filename, "w") as f: and a for loop. write() does not add the newline for you.def save_lines(filename, lines):
with open(filename, "w") as f:
for line in lines:
f.write(line + "\n")
save_lines("shopping.txt", ["eggs", "rice", "apples"])
2. Predict what survives
Predict the output Medium ✓ CompletedThe file is opened four times with different modes. Type exactly what the last line prints.
with open("pets.txt", "w") as f:
f.write("cat\n")
with open("pets.txt", "a") as f:
f.write("dog\n")
with open("pets.txt", "w") as f:
f.write("fish\n")
with open("pets.txt", "a") as f:
f.write("bird\n")
with open("pets.txt") as f:
print(f.read().split())
['fish', 'bird']
2 more exercises → 4 more examples
Questions learners ask
Do I still need to call close() if I use with open()?
No. The with block closes the file automatically when the indented code finishes, even if an error occurs. Without with you must call f.close() yourself, and it is easy to forget.
Why do I get FileNotFoundError when the file is on my computer?
On this site Python runs in your browser, which has its own temporary file system and cannot see your computer's files, so create the file in code first. In desktop Python, a relative name like data.txt is looked up in the current working directory, which may not be the folder your script is in.
What is the difference between read(), readline() and readlines()?
read() returns the whole file as one string, readline() returns the next single line, and readlines() returns a list of all lines. For large files, looping with for line in f is best because it reads one line at a time.
Further reading
10Next lesson
Up nextPython with StatementThe with statement runs setup code before a block and guaranteed cleanup code after it, even when the block fails, by u…Related:
Python with StatementPython pathlibWorking with JSON in PythonPython CSV Files
← Python itertools · All Iteration and Files lessons · Practise in the IDE