Academic Block

Python File HandlingGet Certified

What Is File Handling?

Variables lose their values as soon as a program ends, so any information that must survive, such as a class roster, a game score, or a list of expenses, has to be saved in a file. File handling means opening a file, reading from it or writing to it, and closing it again when you are done. Python makes this simple with the built-in open() function, which gives you a file object that you can read from and write to. Once you can work with files, your programs can store results, load data that other people prepared, and process documents that are far too large to type in by hand.

  • open(): connects your program to a file and returns a file object.
  • File modes: "r" to read, "w" to write, "a" to append, and "x" to create a new file.
  • The with statement: closes the file for you, even when an error occurs.
  • Reading: read(), readline(), readlines(), or a simple for loop over the file.
  • Paths and folders: pathlib and os check, rename, and delete files.
  • CSV files: the csv module reads and writes tables of data.
  • Errors: FileNotFoundError and FileExistsError are the problems you will meet most often.
Note: The code on this page runs inside your browser tab. The files that these examples create live in a temporary, in-memory area that disappears when you reload the page, so you never need to worry about leftover files. On your own computer, the very same code saves real files in a folder. The lesson on browser execution explains the limits of this setup.

Opening Files and File Modes

Every file operation begins with open(filename, mode). The mode tells Python what you plan to do with the file, and it protects you from mistakes, for example by refusing to write to a file that was opened only for reading. If you leave the mode out, Python opens the file for reading text. The best way to work with a file is the with statement, which closes the file automatically at the end of its indented block. Closing matters because data that was written may stay in a buffer until the file is closed, and open files use up system resources.

  • "r" reads a file. It is the default, and it raises FileNotFoundError if the file is missing.
  • "w" writes to a file. It creates the file if needed and erases any existing content.
  • "a" appends to the end of a file and keeps the existing content. It also creates the file if needed.
  • "x" creates a new file and raises FileExistsError if the file already exists, so it never overwrites anything.
  • "r+" reads and writes the same file without erasing it.
  • Add "t" for text, which is the default, or "b" for binary data such as images, as in "rb" and "wb".
  • Pass encoding="utf-8" when a text file may contain accents, symbols, or emoji.

Try It: Writing and Reading a Roster

Click Test My Code. Then add a fourth name to the file and run it again to see the character count change.

What this code does: It opens a file for writing and saves three names, one per line. It then opens the same file for reading, loads the whole content into a variable, and prints the text and its length. The last line shows that the with statement closed the file automatically.
with open("roster.txt", "w") as file:
    file.write("Emma Johnson\n")
    file.write("Liam Smith\n")
    file.write("Olivia Brown\n")

with open("roster.txt", "r") as file:
    content = file.read()

print(content)
print(len(content))
print(file.closed)

Reading Text Files in Different Ways

Python gives you several ways to read a text file, and the right one depends on how much data you have and what you want to do with it. read() loads everything at once, which is fine for small files. readline() reads a single line each time you call it, and readlines() returns all the lines in a list. The most common and most memory-friendly method is to loop over the file object with for, because Python then reads one line at a time and can handle files that are much bigger than your computer’s memory.

  • file.read() returns the rest of the file as one string. file.read(n) returns at most n characters.
  • file.readline() returns the next line, including its \n, or an empty string at the end of the file.
  • file.readlines() returns a list of all remaining lines.
  • for line in file: goes through the lines one at a time and is the usual choice.
  • Every line ends with \n, so use line.strip() to remove it and any extra spaces.
  • file.read().splitlines() gives a list of lines without the line breaks.

Try It: Reading Line by Line

Click Test My Code. Notice how the second read continues where the first one stopped.

What this code does: It saves four city names, one per line. It then reads the first line with readline() and the remaining lines with readlines(), and prints both results with their line breaks visible. Finally it loops over the file with enumerate() and prints each city with a number.
with open("cities.txt", "w") as file:
    file.write("Boston\nChicago\nDenver\nSeattle\n")

with open("cities.txt") as file:
    first = file.readline()
    rest = file.readlines()

print(repr(first))
print(rest)

with open("cities.txt") as file:
    for number, line in enumerate(file, start=1):
        print(number, line.strip())

Writing and Appending to Files

Writing is as easy as reading, but it needs more care, because the wrong mode can destroy data. Mode "w" erases the file before it writes, which is perfect for a fresh report and dangerous for a file that you want to keep. Mode "a" adds new text at the end, which makes it the natural choice for logs, guest books, and any file that grows over time. The write() method accepts only strings and does not add line breaks by itself, so you have to include \n where you want a new line.

  • file.write(text) writes a string and returns the number of characters written.
  • file.writelines(list_of_strings) writes every string of a list. It does not add line breaks either.
  • print(text, file=file) writes like print(), including the line break, into the file.
  • Convert numbers first, for example file.write(str(42)), or use an f-string.
  • Use "x" when you want an error instead of overwriting an existing file.

Try It: Write, Append, and Overwrite

Click Test My Code. Change the second "a" mode to "w" and see which lines survive.

What this code does: It creates a log file with one entry, appends two more entries to it, and prints the whole log. It then opens the file in write mode, which erases the old content and saves a single new line, and finally uses os.path.getsize() to show how small the file has become.
import os

with open("log.txt", "w") as file:
    file.write("Server started in Austin\n")

with open("log.txt", "a") as file:
    file.write("User Ava logged in\n")
    file.write("User Noah logged in\n")

with open("log.txt") as file:
    print(file.read(), end="")

with open("log.txt", "w") as file:
    file.write("Log cleared\n")

print(os.path.getsize("log.txt"), "bytes")

Moving Around in a File: seek() and tell()

An open file keeps an invisible marker called the file position, or cursor, which shows where the next read or write will happen. Reading moves the cursor forward, which is why a second read() on the same open file returns an empty string. The tell() method reports the current position, and seek() jumps to a new one, so you can read a part of a file again or skip ahead. These methods are especially useful for fixed-size records and for re-reading a file without closing and reopening it.

  • file.tell() returns the current position, counted from the start of the file.
  • file.seek(0) jumps back to the beginning, so you can read the file again.
  • file.seek(n) moves to position n.
  • file.read(n) reads n characters and moves the cursor forward by that amount.

Try It: Jumping Around a File

Click Test My Code. Change seek(7) to seek(4) and predict the new output.

What this code does: It saves the letters A to J in a file. It reads the first three characters and shows the cursor position, jumps to position 7 and reads the rest of the file, and finally jumps back to the beginning to read the first two characters again.
with open("alphabet.txt", "w") as file:
    file.write("ABCDEFGHIJ")

with open("alphabet.txt") as file:
    print(file.read(3))
    print(file.tell())
    file.seek(7)
    print(file.read())
    file.seek(0)
    print(file.read(2))

Working with Paths: pathlib and os

Programs often need to ask questions about files before they touch them: does the file exist, what is its extension, and can I rename or delete it? The pathlib module treats a file path as an object with helpful attributes and methods, and it works the same way on every operating system. The older os module offers similar tools as plain functions, such as os.path.exists(), os.rename(), and os.remove(). For copying files, the shutil module provides shutil.copy(). Checking first, and deleting with care, prevents many of the most common file errors.

  • Path("notes.txt") creates a path object. The file does not have to exist yet.
  • path.exists() tells you whether the file or folder exists.
  • path.name, path.stem, and path.suffix give the full name, the name without the extension, and the extension.
  • path.write_text(text) and path.read_text() write and read a whole text file in one call.
  • path.rename(new_name) renames a file, and os.remove(name) deletes it permanently.
  • os.listdir(".") lists the names in a folder, and os.getcwd() shows the current folder.

Try It: Checking, Renaming, and Deleting

Click Test My Code. Follow the file through its life: it does not exist, is created, is renamed, and is deleted.

What this code does: It creates a path object for a file that does not exist yet and checks it. It writes a short text with write_text(), prints the extension and the name of the file, reads the text back, and renames the file. It then confirms that the old name is gone, deletes the new name, and checks one more time.
import os
from pathlib import Path

path = Path("notes.txt")
print(path.exists())
path.write_text("Visit the Grand Canyon\n")
print(path.exists(), path.suffix, path.stem)
print(path.read_text().strip())
path.rename("trip.txt")
print(os.path.exists("notes.txt"), os.path.exists("trip.txt"))
os.remove("trip.txt")
print(os.path.exists("trip.txt"))

Reading and Writing CSV Files

A CSV file, short for comma-separated values, stores a table as plain text: each line is a row, and commas separate the columns. Spreadsheets such as Excel and Google Sheets can open and save this format, which makes it a favorite for exchanging data. Splitting lines at commas yourself breaks as soon as a value contains a comma or a quotation mark, so Python provides the csv module to handle these details correctly. Always open CSV files with newline="", so that the module controls the line endings itself.

  • csv.writer(file) creates a writer. writerow(list) writes one row, and writerows(list_of_lists) writes many rows.
  • csv.reader(file) gives each row as a list of strings.
  • csv.DictReader(file) uses the first row as column names and gives each row as a dictionary.
  • Every value that you read from a CSV file is text, so convert numbers with int() or float().

Try It: A CSV Scoreboard

Click Test My Code. Add a third player to the list and run it again.

What this code does: It defines a table with a header row and two players. It writes the table to a CSV file with csv.writer, then reads the file back with csv.DictReader, which lets the program use the column names to pick out each value and print a sentence for every player.
import csv

players = [
    ["name", "team", "points"],
    ["Jordan Lee", "Lakers", 28],
    ["Maya Davis", "Celtics", 31],
]

with open("scores.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerows(players)

with open("scores.csv", newline="") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row["name"], "scored", row["points"], "for the", row["team"])

Processing a Text File

Real programs rarely just copy a file to the screen: they analyze it. Typical tasks are counting lines and words, searching for a keyword, or adding up numbers that are stored in the file. The pattern is almost always the same: create a few variables before the loop to hold the totals, loop over the file one line at a time, update the totals for every line, and print the results after the loop. Because the loop reads only one line at a time, the same code works for a three-line note and for a file with millions of lines.

  • Create counters or empty lists before the loop, so that they are not reset on every line.
  • line.split() breaks a line into words, and len() counts them.
  • line.strip() removes the line break, and line.lower() makes comparisons case-insensitive.
  • if "keyword" in line: tests whether a line contains some text.

Try It: Counting Lines and Words

Click Test My Code. Add a fourth sentence to the text and check how the totals change.

What this code does: It saves a three-line text in a file. It then loops over the file, adds one to a line counter for each line, and adds the number of words of each line to a word counter. At the end it prints both totals.
text = """Python is fun.
Python is popular in Texas and Ohio.
Learning Python takes practice."""

with open("story.txt", "w") as file:
    file.write(text)

line_count = 0
word_count = 0
with open("story.txt") as file:
    for line in file:
        line_count += 1
        word_count += len(line.split())

print("Lines:", line_count)
print("Words:", word_count)

Handling File Errors

Files live outside your program, so many things can go wrong that your code cannot control: the file may be missing, the folder may not exist, or you may not have permission to write. These problems raise exceptions, and a good program catches them and responds with a helpful message instead of crashing with a traceback. The two most common ones are FileNotFoundError, which occurs when you open a missing file for reading, and FileExistsError, which occurs when you create a file in "x" mode and the name is already taken. Both are kinds of OSError, and the exception object carries useful details such as the file name.

  • FileNotFoundError: opening a missing file with "r". Check the name and the folder.
  • FileExistsError: creating a file with "x" when it already exists.
  • PermissionError: you are not allowed to read or write that file.
  • IsADirectoryError: you tried to open a folder as if it were a file.
  • error.filename and error.strerror give the file name and a short description of the problem.

Try It: Missing and Existing Files

Click Test My Code. Change "missing_file.txt" to "report.txt" in the first block, and see what happens when the file exists.

What this code does: It tries to read a file that does not exist and catches the FileNotFoundError, printing the file name and a description. It then creates a report file and tries to create it again in exclusive mode, which raises a FileExistsError that the program catches, so the original is not overwritten.
try:
    with open("missing_file.txt") as file:
        print(file.read())
except FileNotFoundError as error:
    print("FileNotFoundError:", error.strerror, "->", error.filename)

with open("report.txt", "w") as file:
    file.write("Quarterly report\n")

try:
    with open("report.txt", "x") as file:
        file.write("New report\n")
except FileExistsError:
    print("report.txt already exists, so it was not overwritten")

Working with User Input and Files

Files and user input work well together: the program asks for information, saves it, and later loads it again. This is how guest books, to-do lists, and expense trackers are built. Everything you type with input() arrives as text, which is exactly what text files store, so saving it is easy. Loading it back is different, because the values in a file are text too, and you must convert numbers with int() or float() before you calculate with them. Writing a file and reading it back in the same program is also a good way to test that your code saves data correctly.

Try It: A Guest Book

The Program Input box is already filled with two lines: Sophia Martinez and Phoenix. Click Run Code straight away, then enter your own name and city.

What this code does: It asks for a name and a city. It creates a guest book file with a title and a line of dashes, then appends the visitor’s entry. Finally it reads the file back, splits it into lines, and prints the number of lines followed by each line.
name = input("Your name: ")
city = input("Your city: ")

with open("guestbook.txt", "w") as file:
    file.write("Guestbook\n")
    file.write("---------\n")

with open("guestbook.txt", "a") as file:
    file.write(f"{name} from {city}\n")

with open("guestbook.txt") as file:
    lines = file.read().splitlines()

print("Lines in file:", len(lines))
for line in lines:
    print(line)

Try It: An Expense Tracker

The Program Input box is filled with 20 35.50 14.50. Click Run Code, then enter your own expenses separated by spaces.

What this code does: It reads a line of weekly expenses and saves each amount on its own line of a file. It then reads the file back, converts every line to a number, and adds the numbers up. It prints how many entries were saved, the total, and the average.
amounts = input("Enter weekly expenses in dollars separated by spaces: ").split()

with open("expenses.txt", "w") as file:
    for amount in amounts:
        file.write(amount + "\n")

total = 0
with open("expenses.txt") as file:
    for line in file:
        total += float(line)

print(f"Entries saved: {len(amounts)}")
print(f"Total spent: ${total:.2f}")
print(f"Average: ${total / len(amounts):.2f}")
Tip: Always use the with statement when you open a file, give the file a clear name, and think twice before using mode "w" on a file that you want to keep. If a file might contain accented letters or symbols, add encoding="utf-8" to open() so that the text looks the same on every computer.

Common Mistakes with Files

Most file problems come from a small set of mistakes, and nearly all of them are easy to avoid once you know what to look for. Some mistakes cause a clear error message, such as a missing file, while others silently lose data, such as opening an important file in write mode. Review the list below whenever your program reads nothing, writes the wrong thing, or reports that a file cannot be found.

  • Forgetting to close the file: data may never reach the disk. Use with open(...) as file:, which closes the file for you.
  • Using "w" on a file you want to keep: it erases the content the moment the file is opened. Use "a" to add, or "x" to be safe.
  • Forgetting \n when writing: write() does not add line breaks, so all the text ends up on one line.
  • Writing a number directly: file.write(42) raises a TypeError. Convert it with str(42) or an f-string.
  • Reading the same open file twice: the second read() returns an empty string, because the cursor is at the end. Call seek(0) or reopen the file.
  • A wrong file name or folder: the result is a FileNotFoundError. Check the spelling, the extension, and the current folder.
  • Not stripping lines: each line read from a file ends with \n, so comparisons such as line == "Boston" fail. Use line.strip().
  • Forgetting newline="" with CSV files: on some systems, blank lines appear between the rows.
  • Reading a huge file with read(): it loads everything into memory. Loop over the file instead.

Key Takeaways

File handling lets your programs remember information between runs and work with data that other people created. The points below summarize the essential tools, and they prepare you for the next lesson on JSON, a popular format for saving structured data such as dictionaries and lists. Keep this list in mind whenever you save or load information in a program.

  • open(name, mode) opens a file, and the with statement closes it automatically, even after an error.
  • Mode "r" reads, "w" overwrites, "a" appends, and "x" creates a new file only if it does not exist.
  • Read with read(), readline(), readlines(), or a for loop, which is the best choice for large files.
  • write() accepts only strings and adds no line breaks, so include \n yourself.
  • The file position moves as you read and write. tell() and seek() report and change it.
  • pathlib, os, and shutil check, rename, delete, and copy files.
  • The csv module reads and writes tables, and every value from a file is text until you convert it.
  • Catch FileNotFoundError and FileExistsError so that missing or existing files do not crash your program.

Frequently Asked Questions

These questions come up again and again when students first learn to work with files in Python. The answers are short and practical, and each idea appears in one of the examples above. If something is still unclear, try it yourself: write a small file, read it back, and change one detail at a time to see how the behavior changes.

How do I open and read a file in Python?

Use the with statement and open(), for example with open(“notes.txt”) as file: followed by content = file.read(). The default mode is “r” for reading text. The with statement closes the file automatically when the block ends.

What is the difference between the “w” and “a” modes in Python?

Mode “w” opens a file for writing and erases any existing content first. Mode “a” opens the file for appending, so new text is added to the end and the existing content is kept. Both create the file if it does not exist.

Why should I use the with statement when working with files?

The with statement closes the file automatically when its block ends, even if an error occurs. This makes sure that written data is saved and that the file is released. Without it, you must remember to call file.close() yourself.

How do I read a file line by line in Python?

Loop over the file object, for example for line in file:. Python reads one line at a time, so it works for very large files. Each line ends with a line break, so use line.strip() to remove it. You can also call readline() for one line or readlines() for a list of all lines.

What is the difference between read(), readline(), and readlines() in Python?

The read() method returns the whole rest of the file as one string. The readline() method returns the next single line. The readlines() method returns all the remaining lines as a list of strings. Looping over the file is usually better for big files.

How do I check if a file exists in Python?

Use Path(“notes.txt”).exists() from the pathlib module, or os.path.exists(“notes.txt”) from the os module. Both return True or False. You can also simply try to open the file and catch FileNotFoundError.

How do I delete or rename a file in Python?

Use os.remove(“name.txt”) to delete a file permanently, and os.rename(“old.txt”, “new.txt”) or Path(“old.txt”).rename(“new.txt”) to rename it. Deleted files do not go to a recycle bin, so check the name carefully first.

How do I read and write a CSV file in Python?

Import the csv module and open the file with newline=””. Use csv.writer(file).writerows(rows) to write a table, csv.reader(file) to read rows as lists, and csv.DictReader(file) to read rows as dictionaries with the header names as keys. All values that you read are text.

Ready for the next step?Learn how to save and load structured data with JSON.
Next: Working with JSON →