program tip

파이썬에서“EOF가 아닐 때”에 대한 완벽한 대응은 무엇입니까?

radiobox 2020. 8. 20. 08:08
반응형

파이썬에서“EOF가 아닐 때”에 대한 완벽한 대응은 무엇입니까?


C 또는 Pascal에서 일부 텍스트 파일을 읽으려면 항상 다음 코드 조각을 사용하여 EOF까지 데이터를 읽습니다.

while not eof do begin
  readline(a);
  do_something;
end;

따라서 파이썬에서 어떻게 간단하고 빠르게 할 수 있을까요?


파일을 반복하여 행을 읽습니다.

with open('somefile') as openfileobject:
    for line in openfileobject:
        do_something()

파일 객체는 반복 가능하며 EOF까지 줄을 양보합니다. 파일 객체를 iterable로 사용하면 버퍼를 사용하여 읽기를 수행합니다.

stdin으로 똑같이 할 수 있습니다 (사용할 필요가 없습니다 raw_input():

import sys

for line in sys.stdin:
    do_something()

그림을 완성하기 위해 다음을 사용하여 이진 읽기를 수행 할 수 있습니다.

from functools import partial

with open('somefile', 'rb') as openfileobject:
    for chunk in iter(partial(openfileobject.read, 1024), b''):
        do_something()

여기서 chunk파일에서 한 번에 최대 1024 바이트를 포함하고 openfileobject.read(1024)빈 바이트 문자열을 반환하기 시작 하면 반복이 중지됩니다 .


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)

읽기에서 반환 된 바이트의 부족 외에 Python 에는 eof 테스트while True / break없기 때문에 구문 을 사용해야 합니다.

C에서는 다음이있을 수 있습니다.

while ((ch != '\n') && (ch != EOF)) {
   // read the next ch and add to a buffer
   // ..
}

그러나 파이썬에서는 이것을 가질 수 없습니다.

 while (line=f.readline()):
     # syntax error

파이썬의 표현식 에서는 할당이 허용되지 않기 때문 입니다.

파이썬에서 이것을하는 것은 확실히 관용적입니다 :

# THIS IS IDIOMATIC Python. Do this:
with open('somefile') as f:
    for line in f:
        process(line)

파일을 열고 한 줄씩 읽는 Python 관용구는 다음과 같습니다.

with open('filename') as f:
    for line in f:
        do_something(line)

파일은 위 코드의 끝에서 자동으로 닫힙니다 ( with구성이 처리합니다).

마지막으로 line후행 개행을 보존 한다는 점에 주목할 가치가 있습니다. 다음을 사용하여 쉽게 제거 할 수 있습니다.

line = line.rstrip()

아래 코드 스 니펫을 사용하여 파일 끝까지 한 줄씩 읽을 수 있습니다.

line = obj.readline()
while(line != ''):

    # Do Something

    line = obj.readline()

While there are suggestions above for "doing it the python way", if one wants to really have a logic based on EOF, then I suppose using exception handling is the way to do it --

try:
    line = raw_input()
    ... whatever needs to be done incase of no EOF ...
except EOFError:
    ... whatever needs to be done incase of EOF ...

Example:

$ 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

Or press Ctrl-Z at a raw_input() prompt (Windows, Ctrl-Z Linux)


You can use the following code snippet. readlines() reads in the whole file at once and splits it by line.

line = obj.readlines()

참고URL : https://stackoverflow.com/questions/15599639/what-is-the-perfect-counterpart-in-python-for-while-not-eof

반응형