file.readline(size=-1) -> str/bytes
\n),除非檔案結尾無換行符。size 指定最大位元組/字元數,若超過則在 size 處截斷(可能在行中間)。"" / b""。with open("foo.txt", "r") as f:
line1 = f.readline()
print(f"完整行: {repr(line1)}") # 'This is 1st line\n'
line2 = f.readline(5)
print(f"前 5 字元: {repr(line2)}") # 'This '
完整行: 'This is 1st line\n'
前 5 字元: 'This '
with open("huge.log", encoding="utf-8") as f:
while True:
line = f.readline()
if not line:
break
process(line.rstrip("\n"))
等價且更 Pythonic:
with open("huge.log", encoding="utf-8") as f:
for line in f:
process(line.rstrip("\n"))
readline():單行、可控制最大長度、記憶體 O(1)。readlines():一次全讀成列表、記憶體 O(N)、小檔隨機存取適合。for line in f:語法糖,底層呼叫 readline(),記憶體 O(1)、最推薦。with open("data.bin", "rb") as f:
header = f.readline(4) # 讀前 4 bytes
assert header == b"MAGIC"