open()
Opens a file so you can read its text, write new text, or add lines to the end. Use it with a with block so the file closes itself.
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)open() connects your program to a file on disk and gives you back a file object. You then call methods on it: .read() to get all the text, .write() to save text, or loop over it to get one line at a time.
The second argument, the mode, says what you want to do: "r" reads (the default), "w" writes a new file, "a" adds to the end of a file, and adding "b" ("rb", "wb") works with raw bytes such as images.
Always open files inside a with block: with open("notes.txt") as f:. When the block ends, Python closes the file for you, even if an error happens. Also pass encoding="utf-8", so accented letters and symbols such as € read the same on every computer.
The trap: mode "w" empties the file the moment it opens it, before you write anything. To keep what is there and add more, use "a".
Parameters
| Parameter | What it is |
|---|---|
filerequired | The path to the file, such as "notes.txt" or "data/sales.csv". A relative path starts from the folder the program runs in. |
modeoptional, default 'r' | "r" read, "w" write (empties the file first), "a" append, "x" create a new file only, plus "b" for bytes and "+" for read and write. |
bufferingoptional, default -1 | How much data to collect in memory before reading or writing the disk. Leave it at -1. |
encodingoptional, default None | How text is turned into bytes. Use "utf-8" unless you know the file uses another one. Only for text modes. |
errorsoptional, default None | What to do with bytes that do not fit the encoding: "strict" raises an error, "replace" puts a ?-like mark in their place. |
newlineoptional, default None | Controls how line endings are translated. Use newline="" when you hand the file to the csv module. |
closefdoptional, default True | Advanced: only matters when file is a number (a file descriptor) instead of a path. |
openeroptional, default None | Advanced: a custom function that opens the file at a low level. |
Return value
A file object. In text mode, reading gives strings; in binary mode ("rb"), reading gives bytes().
Examples
1Read a whole file
with open("notes.txt", encoding="utf-8") as f:
text = f.read()
print(text)
print(len(text.splitlines()), "lines")Buy milk Call Sofia Pay rent: 850 EUR 3 lines
The file ends with a new line, so print(text) shows an empty line after the last one.
2Read a file line by line
Looping over a file gives one line at a time, including its \n at the end. strip() removes it.
with open("guests.txt", encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
print(number, line.strip())1 Amara 2 Jonas 3 Mei
3Write a new file, then read it back
items = ["bread", "olive oil", "tomatoes"]
with open("shopping.txt", "w", encoding="utf-8") as f:
for item in items:
f.write(item + "\n")
with open("shopping.txt", encoding="utf-8") as f:
print(f.read())bread olive oil tomatoes
write() does not add a new line for you: add "\n" yourself.
4Add lines to the end with mode "a"
with open("log.txt", "a", encoding="utf-8") as f:
f.write("10:15 backup finished\n")
with open("log.txt", encoding="utf-8") as f:
print(f.read())09:00 server started 10:15 backup finished
The old line is still there. With "w" it would have been erased.
5Read a CSV file and add up a column
total = 0
with open("sales.csv", encoding="utf-8") as f:
next(f) # skip the header line
for line in f:
city, amount = line.strip().split(",")
total += float(amount)
print(f"{city:<8}{amount:>8}")
print(f"Total: {total:.2f}")Athens 120.50 Porto 89.90 Lyon 240.00 Total: 450.40
Common mistakes
Opening a file that is not there
Reading a file that does not exist raises FileNotFoundError. Check the name and folder, or catch the error and tell the user.
try:
with open("missing.txt", encoding="utf-8") as f:
print(f.read())
except FileNotFoundError:
print("Sorry, missing.txt was not found")Sorry, missing.txt was not found
Using "w" when you wanted to add
Mode "w" empties the file as soon as it opens. Everything that was in it is gone. Use "a" to add to the end.
with open("diary.txt", "w", encoding="utf-8") as f:
f.write("Day 2\n")
with open("diary.txt", encoding="utf-8") as f:
print(f.read())Day 2
Forgetting to close the file
Without with, you must call f.close() yourself, and text you wrote may not reach the disk until you do. The with block closes the file for you, so prefer it every time.
Questions people ask
How do I read a file into a list of lines?
Use f.read().splitlines(), which gives the lines without their \n. f.readlines() also works but keeps the \n on each line.
What is the difference between "w" and "a" mode?
"w" starts with an empty file (it erases what was there). "a" keeps the content and writes after it. Both create the file if it does not exist.
Why do I get UnicodeDecodeError when reading a file?
The file is not in the encoding Python guessed. Pass encoding="utf-8"; if that still fails, the file may use another encoding such as "cp1252" or "latin-1".
How do I check if a file exists before opening it?
Use os.path.exists("notes.txt") or pathlib.Path("notes.txt").exists(). Often it is simpler to just open it inside try and catch FileNotFoundError.