3 回答

TA貢獻1155條經驗 獲得超0個贊
您可以在Python中模仿C語言。
要讀取不超過max_size字節數的緩沖區,可以執行以下操作:
with open(filename, 'rb') as f:
while True:
buf = f.read(max_size)
if not buf:
break
process(buf)
或者,一行一行地顯示文本文件:
# warning -- not idiomatic Python! See below...
with open(filename, 'rb') as f:
while True:
line = f.readline()
if not line:
break
process(line)
您需要使用while True / break構造函數,因為除了缺少讀取返回的字節以外,Python中沒有eof測試。
在C語言中,您可能具有:
while ((ch != '\n') && (ch != EOF)) {
// read the next ch and add to a buffer
// ..
}
但是,您不能在Python中使用此功能:
while (line=f.readline()):
# syntax error
因為Python的表達式中不允許賦值。
在Python中這樣做當然更慣用了:
# THIS IS IDIOMATIC Python. Do this:
with open('somefile') as f:
for line in f:
process(line)

TA貢獻1853條經驗 獲得超9個贊
用于打開文件并逐行讀取的Python習慣用法是:
with open('filename') as f:
for line in f:
do_something(line)
該文件將在上述代碼的末尾自動關閉(該with結構將完成此工作)。
最后,值得注意的是line將保留尾隨的換行符。可以使用以下方法輕松刪除它:
line = line.rstrip()
添加回答
舉報