PythonBasicsbeginner

Python File Handling for Beginners

Read, write and append text files in Python with open(), file modes and the with statement, using tiny examples with output.

Published
TL;DR – Quick Answer

File handling in Python means opening a file with open(), reading or writing it, and closing it. open("notes.txt", "w") opens a file for writing, "r" opens it for reading and "a" adds to the end. The usual way is with open(...) as f:, which closes the file for you when the block ends, even if an error happens.

On This Page

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

  1. Open the file with open(). You get a file object back.
  2. Read or write using methods of that file object.
  3. 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 .py file lives. If Python cannot find a file that you can see, run the program from that folder or give the full path, such as r"C:\Users\Ravi\Documents\marks.txt". The r before the string stops Python from treating \U and \n inside 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

  1. open(name, mode) opens a file. The default mode is "r".
  2. "w" overwrites, "a" appends, "r" reads.
  3. with open(...) as f: closes the file for you.
  4. write() needs a string and does not add a newline.
  5. Read with read(), readline(), readlines() or a for loop.
  6. File data is text. Convert numbers with int() or float().

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?
It is the set of steps to work with files from a program: open the file, read from it or write to it, and close it. Python's built-in open() function does most of the work.
What is the difference between w and a mode?
w mode creates the file if needed and deletes everything already in it before writing. a mode keeps the old content and adds new text at the end.
Why should I use with open in Python?
The with statement closes the file automatically when the block ends, even if an error occurs inside it. You do not need to remember to call close().
Does write() add a new line automatically?
No. write() writes exactly the text you give it. Add \n at the end of each line yourself, or use print() with the file argument, which adds a newline for you.
How do I fix FileNotFoundError in Python?
Check the file name and extension, and check that the file is in the folder where you run the program. You can also give the full path, or catch the error with try and except.

Want to Build Your Career in Data Science with AI?

Join CodeBegun and train with working industry engineers — View the Data Science curriculum

Apply for Demo Class →
Siva Prasad Galaba
Founder, CodeBegun · Staff Engineer

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaches Java, Spring Boot and system design the way the industry actually works, and mentors students through projects, mock interviews and placement preparation.

Technically reviewed by CodeBegun Technical TeamLast reviewed 5 December 2026 LinkedIn
Chat with us