Python
open
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.
Exercise 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().
Show example 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()
Test yourself
-
What does open("f.txt", "w") do?
- Opens the file only for reading
- Opens the file for writing; truncates it if it exists
- Appends to the file; old content stays
- Deletes the file and leaves nothing behind
Show answer
Opens the file for writing; truncates it if it exists — The "w" mode opens the file for writing; if the file exists, its content is erased.
-
Complete the write mode
f = open("notes.txt", "____", encoding="utf-8")
f.write("Hello")
f.close()
Show answer
f = open("notes.txt", "w", encoding="utf-8")
f.write("Hello")
f.close()
-
Match the file modes
- r
- Read mode
- w
- Write mode
- a
- Append mode
- x
- Exclusive create mode
Next lesson: read and readline