Mode là chuỗi kết hợp các ký tự:
| Mode | Ý nghĩa |
|---|---|
r | Read (mặc định). File phải tồn tại. |
w | Write. Tạo mới hoặc truncate (xóa nội dung) nếu tồn tại. |
x | Exclusive creation. Fail nếu file đã tồn tại. |
a | Append. Ghi ở cuối file, tạo mới nếu chưa có. |
t | Text mode (mặc định). |
b | Binary mode. |
+ | Update (read + write). |
Kết hợp phổ biến
open('file.txt') # 'rt' - read text
open('file.txt', 'w') # 'wt' - write text
open('file.txt', 'a') # 'at' - append text
open('file.txt', 'r+') # read/write text
open('file.bin', 'rb') # read binary
open('file.bin', 'wb') # write binary
open('file.bin', 'r+b') # read/write binary
open('file.txt', 'x') # create exclusive (fail nếu tồn tại)
Lưu ý
wvàw+**xóa sạch nội dung** file cũ.xan toàn hơnwkhi không muốn ghi đè.aluôn ghi ở cuối, ngay cả khi seek về đầu.