讀一些文本文件,在C或Pascal,我總是用下面的代碼片段來讀取數據,直到EOF:什麼是Python的完美對口「而不是EOF」
while not eof do begin
readline(a);
do_something;
end;
因此,我想知道如何在Python中簡單快速地做到這一點?
讀一些文本文件,在C或Pascal,我總是用下面的代碼片段來讀取數據,直到EOF:什麼是Python的完美對口「而不是EOF」
while not eof do begin
readline(a);
do_something;
end;
因此,我想知道如何在Python中簡單快速地做到這一點?
遍歷文件中讀取行:
with open('somefile') as openfileobject:
for line in openfileobject:
do_something()
File對象是可迭代和產量行,直到EOF。將文件對象用作迭代器使用緩衝區來確保高性能讀取。
你可以做同樣的標準輸入(無需使用raw_input()
:
from functools import partial
with open('somefile', 'rb') as openfileobject:
for chunk in iter(partial(openfileobject.read, 1024), ''):
do_something()
其中chunk
包含了:
import sys
for line in sys.stdin:
do_something()
要完成圖片,二進制讀取可以用做從文件一次到1024字節。
打開文件並逐行讀取它的Python成語是:
with open('filename') as f:
for line in f:
do_something(line)
該文件將在上面的代碼結束時自動關閉(with
構建負責)。
最後,值得注意的是line
將保留尾隨的換行符。這可以很容易地刪除使用:
line = line.rstrip()
+1,同時也向OP指出,這與f.readlines()中非常類似的行不同*:這是一種常用的解決方案。 – jedwards 2013-03-24 14:33:53
你可以在Python中模仿C語言。通過線
with open(filename,'rb') as f:
while True:
buf=f.read(max_size)
if not buf: break
process(buf)
或者,一個文本文件行:
要讀取緩存高達max_size
字節數,你可以做到這一點
# 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中有no eof test,除了缺少從讀取返回的字節外。
在C語言中,你可能有:
while ((ch != '\n') && (ch != EOF)){
// read the next ch and add to a buffer
// ..
}
但是,你不能有這樣的Python:
while(line=f.readline()):
# syntax error
因爲在Python assignments are not allowed in expressions。
這當然是更地道的Python做到這一點:
# THIS IS IDIOMATIC Python. Do this:
with open('somefile') as f:
for line in f:
process(line)
當然,它不會*返回行。 – 2013-03-24 14:42:50
@MartijnPieters:現在它確實:-) – dawg 2013-03-24 14:45:31
作爲C和Perl程序員,你指出** [賦值不允許在表達式中](http://docs.python.org/2/faq/design.html#爲什麼可以使用一個表達式分配)**對我至關重要。 – 2016-05-13 20:00:55
您可以使用下面的代碼片段,以逐行讀取,直到文件結束
line = obj.readline()
while(line != ''):
# Do Something
line = obj.readline()
國際海事組織,這是一個最能反映問題的答案。 – gvrocha 2017-04-22 14:01:41
您可以使用以下代碼片段。 readlines()立即讀入整個文件並逐行分割。
line = obj.readlines()
雖然有上面對於「做巨蟒方式」,如果一個人想真正擁有基於EOF邏輯的建議的話,我想使用異常處理是做到這一點的方式 -
try:
line = raw_input()
... whatever needs to be done incase of no EOF ...
except EOFError:
... whatever needs to be done incase of EOF ...
實施例:
$ echo test | python -c "while True: print raw_input()"
test
Traceback (most recent call last):
File "<string>", line 1, in <module>
EOFError: EOF when reading a line
或按按Ctrl-Z在raw_input()
提示(視窗,按Ctrl-Z Linux)
@TessellatingHeckler這不是[文檔](https://docs.python.org/2/library/exceptions.html#exceptions.EOFError)所說的:「當內置函數之一(輸入( )或raw_input())在不讀取任何數據的情況下達到文件結束條件(EOF)。「 – 2016-05-16 16:49:56
@ TadhgMcDonald-Jensen嘿,所以它會。多麼奇怪。虛假索賠撤回,不公平downvote刪除。 – TessellatingHeckler 2016-05-16 17:31:42
謝謝,順便說一句,我該怎麼做raw_input(),即標準輸入。 – 2013-03-24 14:29:16
你必須使用'sys.stdin'來做到這一點 – jozefg 2013-03-24 14:31:25
謝謝,「sys.stdin」部分真的幫助我。 – 2013-03-24 14:46:03