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

Chế độ 'U' (Universal Newline) khi mở file Python

Mode 'U' (hoặc 'rU') bật Universal Newline Support: tự động chuyển đổi mọi kiểu newline (\n Unix, \r\n Windows, \r Mac cũ) thành \n khi đọc.

Ví dụ

# File Windows có CRLF
# hello.txt nội dung: Hello\r\nworld

with open('hello.txt', 'rU') as f:
    content = f.read()
    print(repr(content))  # 'Hello\nworld'

Lưu ý Python 3

  • Python 3: 'U' deprecated (vẫn hoạt động nhưng warning). Mặc định open() đã universal newline (newline=None).
  • Điều khiển chính xác: newline='' (không convert), newline='\n', newline='\r\n'.
# Python 3 cách hiện đại
open('file.txt', 'r', newline='')      # không convert, giữ nguyên \r\n
open('file.txt', 'r', newline='\n')    # convert về \n
open('file.txt', 'r')                  # mặc định: universal newline (→ \n)