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 địnhopen()đã 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)