When a Python program ends, its variables are gone. If you want to keep data, such as a list of student names or a log of daily expenses, you have to save it in a file. Reading and writing files from a program is called file handling.
This page covers the open() function, file modes, reading, writing, appending, closing and the with statement. Every example uses a tiny text file so you can see exactly what happens. Run the examples in order, in the same folder, because later examples read the files that earlier ones create.
The three steps of file handling
- Open the file with
open(). You get a file object back. - Read or write using methods of that file object.
- Close the file so Python saves everything and frees the file.
f = open("hello.txt", "w")
f.write("Hello from Python\n")
f.close()
f = open("hello.txt", "r")
print(f.read())
f.close()
Output:
Hello from Python
The first part creates hello.txt and writes one line. The second part opens it again and prints its contents. The extra blank line in the output comes from the \n in the file plus the newline that print() adds.
The open() function and file modes
open(file_name, mode)
The mode is a short string that says what you want to do.
| Mode | Name | If the file exists | If the file does not exist |
|---|---|---|---|
"r" |
Read (default) | Opens it for reading | FileNotFoundError |
"w" |
Write | Deletes the old content, then writes | Creates it |
"a" |
Append | Keeps the content, writes at the end | Creates it |
"x" |
Create | FileExistsError |
Creates it |
"r+" |
Read and write | Opens it for both | FileNotFoundError |
Add b for binary files such as images, for example "rb". For text files, which is all this page uses, the plain modes are enough.
Common mistake: Opening an important file with
"w"when you meant"a". Mode"w"empties the file the moment you open it, before you write anything.
The with statement
Forgetting close() is easy, and if an error happens before close(), the line never runs. The with statement fixes both problems. It closes the file automatically when the indented block ends.
with open("students.txt", "w") as f:
f.write("Anjali\n")
f.write("Kiran\n")
f.write("Ravi\n")
print(f.closed)
Output:
True
f.closed is True because the file was closed as soon as the with block finished. From here on, every example uses with. It is the normal way to work with files in Python.
Writing to a file
write() writes exactly the text you give it. It does not add a newline, so put \n at the end of each line.
marks = [72, 85, 64]
with open("marks.txt", "w") as f:
for m in marks:
f.write(str(m) + "\n")
print("Saved", len(marks), "marks")
Output:
Saved 3 marks
After this runs, marks.txt contains:
72
85
64
write() only accepts text. Writing a number directly, such as f.write(72), raises TypeError, which is why the code uses str(m).
Reading a file
There are three common ways to read. All of them use the students.txt file created above.
read(): the whole file as one string
with open("students.txt", "r") as f:
content = f.read()
print(content)
print(len(content))
Output:
Anjali
Kiran
Ravi
18
The length is 18 because it counts every letter plus the three \n characters.
readline(): one line at a time
with open("students.txt") as f:
first = f.readline()
second = f.readline()
print(first.strip())
print(second.strip())
Output:
Anjali
Kiran
Each call moves forward by one line. strip() removes the \n at the end. The mode is left out here because "r" is the default.
Looping over the file
with open("students.txt") as f:
for line in f:
print("Student:", line.strip())
Output:
Student: Anjali
Student: Kiran
Student: Ravi
This is the best way to read a large file, because Python reads one line at a time instead of loading the whole file into memory.
| Method | Returns | Good for |
|---|---|---|
f.read() |
The whole file as one string | Small files |
f.readline() |
The next line as a string | Reading a header or a few lines |
f.readlines() |
A list of all lines | Small files you want as a list |
for line in f |
One line per loop | Any file, including large ones |
Appending to a file
Mode "a" adds to the end and keeps what is already there.
with open("students.txt", "a") as f:
f.write("Meena\n")
with open("students.txt") as f:
names = f.readlines()
print(names)
Output:
['Anjali\n', 'Kiran\n', 'Ravi\n', 'Meena\n']
readlines() keeps the \n at the end of each line. Use [n.strip() for n in names] if you want clean names.
Small program: total and average from a file
This reads marks.txt, converts each line to a number and prints a summary.
total = 0
count = 0
with open("marks.txt") as f:
for line in f:
total += int(line)
count += 1
print("Count:", count)
print("Total:", total)
print("Average:", round(total / count, 2))
Output:
Count: 3
Total: 221
Average: 73.67
Everything read from a text file is a string, so int(line) converts it. int() ignores the newline at the end, so int("72\n") works.
Handling a missing file
Opening a file that does not exist in read mode stops the program.
with open("missing.txt") as f:
print(f.read())
Output (last line):
FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'
Catch the error with try and except to show a friendly message instead:
try:
with open("missing.txt") as f:
print(f.read())
except FileNotFoundError:
print("File not found. Check the name and the folder.")
Output:
File not found. Check the name and the folder.
Pro tip: A relative name such as
"marks.txt"is looked up in the folder you run the program from, not always the folder where the.pyfile lives. If Python cannot find a file that you can see, run the program from that folder or give the full path, such asr"C:\Users\Ravi\Documents\marks.txt". Therbefore the string stops Python from treating\Uand\ninside the path as special characters.
Common file handling mistakes
| Mistake | What happens | Fix |
|---|---|---|
Using "w" instead of "a" |
Old content is deleted | Use "a" to add to a file |
Forgetting \n in write() |
All text ends up on one line | Add "\n" at the end of each line |
| Writing a number | TypeError: write() argument must be str, not int |
Convert with str() |
| Not closing the file | Data may not be saved yet | Use with open(...) |
| Wrong folder or name | FileNotFoundError |
Check the path, or use the full path |
| Treating file data as numbers | "72" + "85" gives "7285" |
Convert each line with int() or float() |
Quick revision
open(name, mode)opens a file. The default mode is"r"."w"overwrites,"a"appends,"r"reads.with open(...) as f:closes the file for you.write()needs a string and does not add a newline.- Read with
read(),readline(),readlines()or aforloop. - File data is text. Convert numbers with
int()orfloat().
File handling is the first step towards real automation, such as reading a list of names, writing reports or cleaning data. See what Python is used for for more real tasks, and use a Python dictionary when each line of your file has a name and a value you want to look up.
Frequently Asked Questions
What is file handling in Python?
What is the difference between w and a mode?
Why should I use with open in Python?
Does write() add a new line automatically?
How do I fix FileNotFoundError in Python?
Want to Build Your Career in Data Science with AI?
Join CodeBegun and train with working industry engineers — View the Data Science curriculum

