Every variable in your program disappears the moment the program ends. If you want to keep data, like a list of student marks, a game's high score or a log of events, you need to store it in a file.
File handling is how Python reads data from files and writes data into them. In this chapter, you'll learn to create, read, write and append to text files safely, and use the exception handling you learned in the previous chapter to deal with missing files.
The Basic Idea
Working with any file always follows three steps:
1. Open the file -> open("notes.txt", "w")
2. Read or write -> file.read() / file.write()
3. Close the file -> file.close() (done for you by "with")The built-in open() function returns a file object, which you then use to read or write.
file = open("notes.txt", "w", encoding="utf-8")"notes.txt"is the file name (or path). A plain name means the file is in the folder you run the program from."w"is the mode: what you want to do with the file.encoding="utf-8"tells Python how to convert text to bytes. Always include it (explained below).
File Modes
| Mode | Meaning | If file exists | If file doesn't exist |
|---|---|---|---|
"r" | Read (default) | Reads it | FileNotFoundError |
"w" | Write | Erases all content first | Creates it |
"a" | Append | Adds to the end | Creates it |
"x" | Exclusive create | FileExistsError | Creates it |
"r+" | Read and write | Opens without erasing | FileNotFoundError |
Add "b" for binary files such as images or PDFs, for example "rb" or "wb". In binary mode you work with bytes instead of strings and you do not pass an encoding.
Warning:
"w"mode deletes everything in the file the moment you open it, even if you never write anything. Use"a"when you want to keep the existing content.
The with Statement
If you open a file, you must close it, otherwise data may not be saved and the file stays locked. But if an exception happens before close(), that line never runs. The with statement solves this:
with open("notes.txt", "w", encoding="utf-8") as file:
print(file.closed)
print(file.closed)Output:
False
TrueInside the with block the file is open. As soon as the block ends, whether normally or because of an exception, Python closes the file automatically. It works like a built-in try/finally. Always use with for files.
Writing to a File
with open("notes.txt", "w", encoding="utf-8") as file:
file.write("Python is fun\n")
file.write("Files are easy\n")
file.write("Practice daily\n")This creates notes.txt containing:
Python is fun
Files are easy
Practice dailyTwo things to notice:
write()does not add a newline automatically likeprint()does. You must add\nyourself.write()only accepts strings.file.write(42)raisesTypeError: write() argument must be str, not int, so convert numbers withstr()or an f-string first.
Writing a list of items
fruits = ["Apple", "Banana", "Mango"]
with open("fruits.txt", "w", encoding="utf-8") as file:
for fruit in fruits:
file.write(fruit + "\n")Each fruit goes on its own line.
Reading from a File
Python gives you several ways to read. Assume notes.txt contains the three lines written above.
read() - the whole file as one string
with open("notes.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)Output:
Python is fun
Files are easy
Practice daily(There is also an extra blank line at the end, because the file's last line ends with \n and print() adds one more.)
readline() - one line at a time
with open("notes.txt", encoding="utf-8") as file:
first = file.readline()
second = file.readline()
print(repr(first))
print(repr(second))Output:
'Python is fun\n'
'Files are easy\n'The file object remembers its position, so each call continues where the last one stopped. Each line keeps its \n at the end. When the file is finished, readline() returns an empty string "".
readlines() - a list of all lines
with open("notes.txt", encoding="utf-8") as file:
lines = file.readlines()
print(lines)Output:
['Python is fun\n', 'Files are easy\n', 'Practice daily\n']Looping over the file - the best way
A file object can be used directly in a for loop. It reads one line per iteration, so it works even for huge files that would not fit in memory:
with open("notes.txt", encoding="utf-8") as file:
for line in file:
print(line.strip())Output:
Python is fun
Files are easy
Practice dailyWhy strip()? Without it, each line's own \n plus print()'s newline would put a blank line between every line.
| Method | Returns | Best for |
|---|---|---|
read() | One string | Small files |
readline() | One line (string) | Reading just the first few lines |
readlines() | List of strings | Small files when you need a list |
for line in file | One line per loop | Any size, especially large files |
Appending to a File
Mode "a" adds new content at the end without touching what is already there:
with open("notes.txt", "a", encoding="utf-8") as file:
file.write("Never give up\n")
with open("notes.txt", encoding="utf-8") as file:
print(file.read(), end="")Output:
Python is fun
Files are easy
Practice daily
Never give upAppending is perfect for log files, where you keep adding new entries over time.
Handling File Errors
Opening a file that does not exist in read mode raises FileNotFoundError. Handle it with try/except:
try:
with open("missing.txt", encoding="utf-8") as file:
print(file.read())
except FileNotFoundError as e:
print("Error:", e)Output:
Error: [Errno 2] No such file or directory: 'missing.txt'You can also check first whether a file exists using the pathlib module from the standard library:
from pathlib import Path
print(Path("notes.txt").exists())
print(Path("missing.txt").exists())Output:
True
FalseOther errors you may meet: PermissionError (no permission to open the file) and IsADirectoryError (the path is a folder; on Windows this case raises PermissionError instead). Both are children of OSError.
Why Always Specify encoding="utf-8"?
Text files are stored as bytes, and the encoding decides how characters map to bytes. If you leave it out, Python 3.14 and earlier use the operating system's default encoding, which on Windows is often not UTF-8 (for example cp1252). A file with characters like ₹ or Hindi text written on one machine may then fail to read on another with a UnicodeDecodeError.
Python 3.15 (released in October 2026) changes the default to UTF-8 on every platform, but writing encoding="utf-8" explicitly makes your code work the same on every version and every machine.
A Practical Example: Processing Marks
Suppose marks.txt contains one student per line:
Asha,91
Ravi,78
Meera,85Let's read it and calculate the average:
total = 0
count = 0
with open("marks.txt", encoding="utf-8") as file:
for line in file:
name, mark = line.strip().split(",")
total += int(mark)
count += 1
print(name, "scored", mark)
print("Average:", round(total / count, 2))Output:
Asha scored 91
Ravi scored 78
Meera scored 85
Average: 84.67Everything read from a text file is a string, so we convert the mark with int() before adding.
Bonus: CSV Files
Comma-separated files like the one above are so common that Python has a built-in csv module. It correctly handles tricky cases like values that contain commas.
import csv
with open("students.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["name", "branch", "cgpa"])
writer.writerow(["Asha", "CSE", 9.1])
writer.writerow(["Ravi", "IT", 8.4])
with open("students.csv", newline="", encoding="utf-8") as file:
for row in csv.reader(file):
print(row)Output:
['name', 'branch', 'cgpa']
['Asha', 'CSE', '9.1']
['Ravi', 'IT', '8.4']Notice that 9.1 came back as the string '9.1'. CSV files store only text. The newline="" argument is recommended by the Python docs whenever you use the csv module, to avoid extra blank lines on Windows.
Common Mistakes
Opening with
"w"by accident and wiping a file you meant to read or extend.Forgetting
\ninwrite(), so everything ends up on one line.Forgetting that file data is a string.
"91" + 5fails; convert withint()orfloat().Not using
with, leaving files open when an error occurs.Reading a file twice from the same object. After
read()the position is at the end, so a secondread()returns"". Open the file again (or usefile.seek(0)to go back to the start).Wrong path. A relative name like
"data.txt"is searched in the folder you run the program from, not necessarily where the script is saved.
Summary
Use
open(name, mode, encoding="utf-8")inside awithblock so the file closes automatically."r"reads,"w"overwrites,"a"appends,"x"creates only if the file is new.write()needs strings and does not add newlines.Loop over the file object to read line by line efficiently.
Catch
FileNotFoundErrorwhen a file might be missing.
Open with
with, choose the right mode, and remember: everything in a text file is a string.
Practice: Write a program that asks the user for tasks and appends each one to todo.txt, then prints all tasks with numbers. Next, try a program that counts the number of lines and words in any text file.