Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Các mode mở file trong Python (r, w, a, x, b, t, +)

Mode là chuỗi kết hợp các ký tự:

ModeÝ nghĩa
rRead (mặc định). File phải tồn tại.
wWrite. Tạo mới hoặc truncate (xóa nội dung) nếu tồn tại.
xExclusive creation. Fail nếu file đã tồn tại.
aAppend. Ghi ở cuối file, tạo mới nếu chưa có.
tText mode (mặc định).
bBinary 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 ý

  • w và w+ **xóa sạch nội dung** file cũ.
  • x an toàn hơn w khi không muốn ghi đè.
  • a luôn ghi ở cuối, ngay cả khi seek về đầu.