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

Đọc toàn bộ file vào string trong Python (read())

Gọi file.read() không đối số → đọc toàn bộ nội dung file vào một string (text mode) hoặc bytes (binary mode).

Ví dụ

with open('my_file.txt', 'r') as f:
    file_content = f.read()  # đọc hết
    print(file_content)

Lưu ý

  • File lớn → tốn RAM, có thể MemoryError.
  • File binary → dùng 'rb' mode, trả về bytes.

Đọc toàn bộ lines thành list

with open('file.txt') as f:
    lines = f.readlines()  # list các dòng, giữ '\n'
    # hoặc
    lines = f.read().splitlines()  # bỏ '\n'

Best practice: with statement

Luôn dùng with open(...) as f: để tự động đóng file (context manager), tránh leak file descriptor.