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
withstatement: closes the file for you, even when an error occurs. - Reading:
read(),readline(),readlines(), or a simpleforloop over the file. - Paths and folders:
pathlibandoscheck, rename, and delete files. - CSV files: the
csvmodule reads and writes tables of data. - Errors:
FileNotFoundErrorandFileExistsErrorare 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 raisesFileNotFoundErrorif 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 raisesFileExistsErrorif 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.
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)open("roster.txt", "w") creates the file, or empties it if it already exists. The with statement stores the file object in the variable file and closes the file when the indented block ends.write() adds text to the file. The \n at the end is a line break. Without it, the names would run together on one line."r" opens the existing file for reading. Because it is the default mode, you could leave it out.read() returns the whole content of the file as one string, including the line breaks.print() adds another one, an empty line follows.37.with block closed the file when it ended. The output is True.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 mostncharacters.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 useline.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.
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())cities.txt is created and opened for writing.write() can contain several line breaks. The file now has four lines."r".readline() returns the first line, including its line break: "Boston\n". The file position moves to the start of the second line.readlines() continues from the current position and returns all the remaining lines in a list.repr() shows the text as Python would write it, so that the line break is visible. The output is 'Boston\n'.['Chicago\n', 'Denver\n', 'Seattle\n'].for loop. It produces one line per repetition, and enumerate() adds a counter that starts at 1.strip() removes the line break so that print() does not add an empty line. The output is four lines: 1 Boston, 2 Chicago, 3 Denver, and 4 Seattle.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 likeprint(), 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.
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")os module gives access to file information such as the size of a file."w" creates log.txt and starts it empty, even if an older file with that name existed."a" keeps the existing content and places the writing position at the end of the file.end="" stops print() from adding an empty line. The output is three lines: Server started in Austin, User Ava logged in, and User Noah logged in."w" erases everything that was in the file. The three entries are gone as soon as the file is opened.Log cleared.os.path.getsize() returns the size in bytes. The text Log cleared has 11 characters plus 1 for the line break. The output is 12 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 positionn.file.read(n)readsncharacters 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.
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))alphabet.txt is created.read(3) returns the first three characters and moves the cursor to position 3. The output is ABC.tell() reports where the cursor is now. The output is 3.seek(7) moves the cursor to position 7, which is in front of the letter H. Nothing is printed.read() without a number reads from the cursor to the end of the file. The output is HIJ.seek(0) moves the cursor back to the beginning of the file.AB.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, andpath.suffixgive the full name, the name without the extension, and the extension.path.write_text(text)andpath.read_text()write and read a whole text file in one call.path.rename(new_name)renames a file, andos.remove(name)deletes it permanently.os.listdir(".")lists the names in a folder, andos.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.
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"))os module provides os.path.exists() and os.remove().Path class from pathlib represents a file path as an object.path refers to the name notes.txt. Creating a path object does not create a file.False.write_text() opens the file, writes the text, and closes the file in a single call. This creates notes.txt.suffix is the extension and stem is the name without it. The output is True .txt notes.read_text() returns the whole content, and strip() removes the final line break. The output is Visit the Grand Canyon.notes.txt is renamed to trip.txt. Nothing is printed.False True.os.remove() deletes trip.txt permanently. There is no recycle bin, so be careful with it.False.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, andwriterows(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()orfloat().
Try It: A CSV Scoreboard
Click Test My Code. Add a third player to the list and run it again.
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"])csv module reads and writes comma-separated files.players is a list of lists. Each inner list will become one row of the file.newline="" lets the csv module control the line endings, which prevents stray blank lines in the file.csv.writer(file) wraps the file in a writer object that knows the CSV format.writerows() writes every inner list as one line. The file contains name,team,points, Jordan Lee,Lakers,28, and Maya Davis,Celtics,31. Numbers are converted to text automatically.newline="" as the csv module recommends.DictReader takes the first line as the column names and turns every following line into a dictionary.{'name': 'Jordan Lee', 'team': 'Lakers', 'points': '28'}.print() shows them normally. The output is Jordan Lee scored 28 for the Lakers and Maya Davis scored 31 for the Celtics.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, andlen()counts them.line.strip()removes the line break, andline.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.
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)Python is fun.story.txt is created and opened for writing.line_count starts at zero. It is created before the loop so that it is not reset on every line.word_count also starts at zero.line.split() breaks the line into a list of words, and len() counts them. The three lines have 3, 7, and 4 words.Lines: 3.Words: 14.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.filenameanderror.strerrorgive 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.
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")except line.missing_file.txt, so open() raises a FileNotFoundError right here.FileNotFoundError and stores the exception object in error.error.strerror is a short description, and error.filename is the name that could not be found. The output is FileNotFoundError: No such file or directory -> missing_file.txt."w" creates report.txt, or replaces it if an older file with that name exists.try."x" means “create a new file, but never replace an existing one”. Because report.txt already exists, open() raises a FileExistsError.FileExistsError runs. It does not need the exception object, so it leaves out as error.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.
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)input() reads the first input line, Sophia Martinez, and stores it as text.Phoenix, is stored in city."w" creates the guest book and removes any old entries, so that every run starts from the same point.Guestbook."a" keeps the title and the divider, and adds new text at the end.Sophia Martinez from Phoenix, and the \n ends the line.read().splitlines() returns a list of the lines without their line breaks. The list has three items.Lines in file: 3.Guestbook, ---------, and Sophia Martinez from Phoenix.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.
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}")["20", "35.50", "14.50"]. All three amounts are still text.expenses.txt is created, or emptied if it already exists.amount takes each text value in turn."\n" directly. The file ends up with three lines: 20, 35.50, and 14.50.total starts at zero, before the loop.line is a text such as "35.50\n".float() turns the text into a number and ignores the line break at the end. The total grows to 20.0, then 55.5, and finally 70.0.Entries saved: 3.Total spent: $70.00.Average: $23.33.Tip: Always use thewithstatement 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, addencoding="utf-8"toopen()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
\nwhen writing:write()does not add line breaks, so all the text ends up on one line. - Writing a number directly:
file.write(42)raises aTypeError. Convert it withstr(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. Callseek(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 asline == "Boston"fail. Useline.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 thewithstatement 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 aforloop, which is the best choice for large files. write()accepts only strings and adds no line breaks, so include\nyourself.- The file position moves as you read and write.
tell()andseek()report and change it. pathlib,os, andshutilcheck, rename, delete, and copy files.- The
csvmodule reads and writes tables, and every value from a file is text until you convert it. - Catch
FileNotFoundErrorandFileExistsErrorso 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.