open
- Python course
- Intermediate
- Lesson 64/116
- 5 min
Learn to open files with open().
Opening a file with open
In Python you open a file with the open function. open("notes.txt", "r") opens the file in read mode and returns a file object. The second argument is the mode: "r" for read, "w" for write, "a" for append.
If you write Turkish text, add the encoding="utf-8" parameter. Without it, the system's default encoding kicks in and Turkish letters may break. When you're done, close the file with f.close().
The encoding parameter
When opening a file, the encoding parameter states which encoding the text uses. For files with Turkish characters, encoding="utf-8" is the safest choice.
If you skip it, Python uses the system's default encoding: cp1254 on Windows and usually utf-8 on Linux. The same code can produce different results on different systems. Writing encoding="utf-8" explicitly makes the code portable.
Practice Write to a file, close, reopen and read
Open a file for writing: f = open("notes.txt", "w", encoding="utf-8"). Write text with f.write("Hello world") and close it with f.close(). Reopen the same file in read mode: f = open("notes.txt", "r", encoding="utf-8"). Print its content with print(f.read()) and close it with f.close().
Starter code
# Open the file in write mode, write Hello world, close
# Reopen the same file in read mode, print its content, closeSample solution
# Open the file in write mode, write Hello world, close
f = open("notes.txt", "w", encoding="utf-8")
f.write("Hello world")
f.close()
# Reopen the same file in read mode, print its content, close
f = open("notes.txt", "r", encoding="utf-8")
print(f.read())
f.close()Expected output
Hello world
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does open("f.txt", "w") do?
- Opens the file only for reading
- Opens the file for writing; truncates it if it exists Correct answer
- Appends to the file; old content stays
- Deletes the file and leaves nothing behind
Explanation: The "w" mode opens the file for writing; if the file exists, its content is erased.
2 Complete the write mode
f = open("notes.txt", "____", encoding="utf-8")
f.write("Hello")
f.close()
f = open("notes.txt", "w", encoding="utf-8")
f.write("Hello")
f.close()
Explanation: The "w" mode opens the file for writing.
3 Match the file modes
| Term | Meaning |
|---|---|
r |
Read mode |
w |
Write mode |
a |
Append mode |
x |
Exclusive create mode |