Intermediate Chapter 97 · 30 min read · Module 8: File Handling
Opening Files
- After this chapter you can choose the right mode for opening a file.
- You can use the encoding argument and explain why it matters.
- You can read the name, mode and closed attributes of a file object.
- You can open a file safely with with, and handle FileNotFoundError, PermissionError and FileExistsError.
- You can use x and r+ modes and describe how they differ from w and a.
Every file operation in Python begins with the built-in function open(). It asks the operating system for access to a file and gives you back a file object. Through that object you read, write, move around and finally close the file.
The most important decision when you call open() is the mode: do you want to read, replace, add to or exclusively create the file? A wrong choice can erase data or raise an error, so it pays to know the modes well.
This chapter explains the signature of open(), every common mode, the encoding setting, the useful attributes of file objects, and the errors you may meet. All examples create their own files, so you can run them as they are.
The open() function
The most used form is open(file, mode='r', encoding=None). The file is a path as text or as a Path object. The mode is a short text that says how to open the file. The encoding says how characters become bytes, and it applies only to text mode. There are more options, such as newline and errors, but these three are enough for most work.
File modes
| Mode | Meaning | If the file is missing | Old content |
|---|---|---|---|
| r | read (default) | FileNotFoundError | kept |
| w | write | created | erased |
| a | append at the end | created | kept |
| x | create exclusively | created | error if file exists |
| r+ | read and write | FileNotFoundError | kept |
| w+ | write and read | created | erased |
Add b for binary mode, as in rb or wb, and t for text mode, which is the default. For example ab appends bytes. The x mode is the safest way to create a new file, because it refuses to overwrite one that already exists and raises FileExistsError instead.
with open("log.txt", "w", encoding="utf-8") as f:
f.write("start\n")
with open("log.txt", "a", encoding="utf-8") as f:
f.write("middle\n")
f.write("end\n")
with open("log.txt", encoding="utf-8") as f:
print(f.read(), end="")
with open("log.txt", "w", encoding="utf-8") as f:
pass
print(repr(open("log.txt").read()))The first open creates the file with one line. The append open keeps it and adds two more lines. The last w open erases everything, so reading gives an empty string.
Attributes of a file object
A file object knows its own name, its mode and whether it is closed. You can call close() yourself, but the with statement is better because it closes the file even if an exception occurs. After the block, the object still exists, but any read or write raises ValueError: I/O operation on closed file.
with open("info.txt", "w", encoding="utf-8") as f:
print(f.name)
print(f.mode)
print(f.closed)
f.write("data")
print(f.closed)
try:
f.write("more")
except ValueError as e:
print(e)Encoding
Computers store bytes, not letters. An encoding is the rule that maps characters to bytes. UTF-8 is the standard choice and it can represent every language. If you leave out the argument, Python uses a system default that may differ between Windows, Linux and macOS, so a file that works on your computer can show strange characters on another. Writing encoding="utf-8" makes the program behave the same everywhere. Python 3.15 is expected to make UTF-8 the default, but it is still wise to be explicit.
text = "café"
with open("c.txt", "w", encoding="utf-8") as f:
f.write(text)
with open("l.txt", "w", encoding="latin-1") as f:
f.write(text)
with open("c.txt", "rb") as f:
print(len(f.read()))
with open("l.txt", "rb") as f:
print(len(f.read()))Exclusive creation and read-write
Mode x is useful when you must not destroy existing data. Mode r+ opens an existing file for both reading and writing, and the position starts at the beginning, so a write replaces characters from there on. The method seek(0) moves back to the start, and tell() tells the current position.
with open("once.txt", "x", encoding="utf-8") as f:
f.write("hello world")
try:
open("once.txt", "x")
except FileExistsError:
print("already exists")
with open("once.txt", "r+", encoding="utf-8") as f:
f.write("HELLO")
f.seek(0)
print(f.read())Errors when opening
| Error | Typical cause |
|---|---|
| FileNotFoundError | reading a file or folder that does not exist |
| PermissionError | no right to read or write that file |
| IsADirectoryError | the path is a folder, not a file |
| FileExistsError | mode x on a file that already exists |
| UnicodeDecodeError | the file was written with a different encoding |
All of these except the last are kinds of OSError, so catching OSError handles them together. Catch the most specific error first when you want different messages. You can also open several files in one with by separating them with commas, which is handy when you copy from one file to another.
with open("src.txt", "w", encoding="utf-8") as f:
f.write("alpha\nbeta\n")
with open("src.txt", encoding="utf-8") as a, open("dst.txt", "w", encoding="utf-8") as b:
for line in a:
b.write(line.upper())
print(open("dst.txt", encoding="utf-8").read(), end="")Many beginners wonder why Python has so many modes. The reason is safety and clarity. Each mode states your intention: when you write r, Python promises not to change the file; when you write a, Python promises not to erase it; and when you write x, Python promises not to replace something that is already there. If your intention and the file do not match, you get an error at once, which is much better than silently losing data. Think about what you want before you type the mode, and choose the most careful one that does the job.
Python syntax
open(file, mode="r", encoding="utf-8")with open(path, "w", encoding="utf-8") as f:
f.write(text)with open(a) as src, open(b, "w") as dst:
...open(path, "x") # fails if it existsReal-world applications
- Appending messages to a log file
- Creating a report file only if it is new
- Updating a few characters of a file in place
- Copying and transforming one file into another
- Reading data files written by other programs
Common mistakes
Fix: Use a to add to the end, or x to protect existing files.
Fix: Always write encoding="utf-8" for text files.
Fix: Do all file work inside the with block.
Fix: Open a file path, or list the folder with Path.iterdir().
Fix: Move with seek() before writing where you want the change.
Important tips
- Prefer with for every file.
- Use x when losing existing data would be a serious problem.
- Catch OSError for a broad file problem and a specific class for a special message.
Key points summary
- open() returns a file object.
- r reads, w erases, a appends, x creates exclusively.
- + gives read and write; b gives bytes.
- Use encoding="utf-8" for text files.
- with closes the file automatically.
Exam and interview points
- open() returns a file object.
- Mode w truncates; mode a never does.
- x raises FileExistsError for an existing file.
- r+ requires the file to exist.
Quick revision
- r w a x + b t
- with = automatic close
- UTF-8 is the safe encoding
- OSError family for open failures
Frequently asked questions
What is the default mode of open()?
It is r, which means read text.
What is the difference between w and x?
Both create a file, but w erases an existing file and x raises FileExistsError instead.
Do I have to call close() when I use with?
No. The with statement closes the file for you at the end of the block.
Why does my text show strange symbols?
The file was probably saved with a different encoding than the one used to read it.
Practise this chapter
23 practice questions Take the chapter quiz