programing

파일이 'eof'에 있는지 확인하는 방법은 무엇입니까?

sourcetip 2021. 1. 16. 11:14
반응형

파일이 'eof'에 있는지 확인하는 방법은 무엇입니까?


fp = open("a.txt")
#do many things with fp

c = fp.read()
if c is None:
    print 'fp is at the eof'

위의 방법 외에도 fp가 이미 eof에 있는지 확인하는 다른 방법이 있습니까?


fp.read()파일의 끝까지 읽으므로 성공적으로 완료되면 파일이 EOF에 있음을 알 수 있습니다. 확인할 필요가 없습니다. EOF에 도달 할 수 없으면 예외가 발생합니다.

를 사용하지 않고 청크 단위로 파일을 읽을 read()read요청한 바이트 수보다 적은 수를 반환 할 때 EOF를 쳤음을 알 수 있습니다. 이 경우 다음 read호출은 빈 문자열 (아님 None)을 반환합니다 . 다음 루프는 청크로 파일을 읽습니다. read한 번만 너무 많이 호출 합니다.

assert n > 0
while True:
    chunk = fp.read(n)
    if chunk == '':
        break
    process(chunk)

또는 더 짧게 :

for chunk in iter(lambda: fp.read(n), ''):
    process(chunk)

"for-else"디자인은 종종 간과됩니다. 참조 : Python Docs "Control Flow in Loop" :

with open('foobar.file', 'rb') as f:
    for line in f:
        foo()

    else:
        # No more lines to be read from file
        bar()

나는 파일에서 읽는 것이 더 많은 데이터를 포함하는지 여부를 확인하는 가장 신뢰할 수있는 방법이라고 주장합니다. 파이프이거나 다른 프로세스가 파일 등에 데이터를 추가 할 수 있습니다.

이것이 문제가 아니라는 것을 알고 있다면 다음과 같이 사용할 수 있습니다.

f.tell() == os.fstat(f.fileno()).st_size

바이너리 I / O를 수행 할 때 다음 방법이 유용합니다.

while f.read(1):
    f.seek(-1,1)
    # whatever

장점은 때때로 바이너리 스트림을 처리하고 있으며 얼마나 읽어야할지 미리 알지 못한다는 것입니다.


파이썬은 "EOF"자체가 아니라 EOF에 빈 문자열을 반환하므로 여기에 작성된 코드를 확인할 수 있습니다.

f1 = open("sample.txt")

while True:
    line = f1.readline()
    print line
    if ("" == line):
        print "file finished"
        break;

메서드 fp.tell()호출 전후 의 반환 값을 비교할 수 있습니다 read. 동일한 값을 반환하면 fp는 eof에 있습니다.

또한 예제 코드가 실제로 작동한다고 생각하지 않습니다. read내 지식 결코 반환에 대한 방법 None,하지만 EOF에 빈 문자열을 반환 않습니다.


읽기는 EOF가 발견되면 빈 문자열을 반환합니다. 문서가 여기 있습니다 .


f=open(file_name)
for line in f:
   print line

파일이 비 블록 모드에서 열리면 예상보다 적은 바이트를 반환하는 것이 eof에 있다는 것을 의미하지는 않습니다. @NPE의 대답이 가장 신뢰할 수있는 방법이라고 말하고 싶습니다.

f.tell () == os.fstat (f.fileno ()). st_size


나는 왜 파이썬이 여전히 그러한 기능을 가지고 있지 않은지 이해하지 못합니다. 나는 또한 다음을 사용하는 것에 동의하지 않습니다

f.tell() == os.fstat(f.fileno()).st_size

주된 이유는 f.tell()특정 조건에서 작동하지 않을 가능성이 있기 때문입니다 .

나를 위해 작동하는 방법은 다음과 같습니다. 다음과 같은 의사 코드가있는 경우

while not EOF(f):
     line = f.readline()
     " do something with line"

다음으로 바꿀 수 있습니다.

lines = iter(f.readlines())
while True:
     try:
        line = next(lines)
        " do something with line"
     except StopIteration:
        break

이 방법은 간단하며 대부분의 코드를 변경할 필요가 없습니다.


Python 읽기 함수는 EOF에 도달하면 빈 문자열을 반환합니다.


f = open(filename,'r')
f.seek(-1,2)     # go to the file end.
eof = f.tell()   # get the end of file location
f.seek(0,0)      # go back to file beginning

while(f.tell() != eof):
    <body>

당신이 사용할 수있는 방법은 파일 추구 ()TELL ()를 파일 끝의 위치를 결정합니다. 위치를 찾으면 파일 시작 부분으로 돌아갑니다.


tell()다음 과 같이 메소드 EOF를 호출 하여 도달 후 메소드 를 사용할 수 있습니다 readlines().

fp=open('file_name','r')
lines=fp.readlines()
eof=fp.tell() # here we store the pointer
              # indicating the end of the file in eof
fp.seek(0) # we bring the cursor at the begining of the file
if eof != fp.tell(): # we check if the cursor
     do_something()  # reaches the end of the file

파일의 EOF 위치를 가져옵니다.

def get_eof_position(file_handle):
    original_position = file_handle.tell()
    eof_position = file_handle.seek(0, 2)
    file_handle.seek(original_position)
    return eof_position

현재 위치와 비교합니다 : get_eof_position == file_handle.tell().


개인적 with으로 파일 열기 및 닫기를 처리하기 위해 문을 사용하지만 stdin에서 읽어야하고 EOF 예외를 추적해야하는 경우 다음과 같이하십시오.

EOFError예외로 try-catch를 사용하십시오 .

try:
    input_lines = ''
    for line in sys.stdin.readlines():
        input_lines += line             
except EOFError as e:
    print e

Reading a file in batches of BATCH_SIZE lines (the last batch can be shorter):

BATCH_SIZE = 1000  # lines

with open('/path/to/a/file') as fin:
    eof = False
    while eof is False:
        # We use an iterator to check later if it was fully realized. This
        # is a way to know if we reached the EOF.
        # NOTE: file.tell() can't be used with iterators.
        batch_range = iter(range(BATCH_SIZE))
        acc = [line for (_, line) in zip(batch_range, fin)]

        # DO SOMETHING WITH "acc"

        # If we still have something to iterate, we have read the whole
        # file.
        if any(batch_range):
            eof = True

Python doesn't have built-in eof detection function but that functionality is available in two ways: f.read(1) will return b'' if there are no more bytes to read. This works for text as well as binary files. The second way is to use f.tell() to see if current seek position is at the end. If you want EOF testing not to change the current file position then you need bit of extra code.

Below are both implementations.

Using tell() method

import os

def is_eof(f):
  cur = f.tell()    # save current position
  f.seek(0, os.SEEK_END)
  end = f.tell()    # find the size of file
  f.seek(cur, os.SEEK_SET)
  return cur == end

Using read() method

def is_eof(f):
  s = f.read(1)
  if s != b'':    # restore position
    f.seek(-1, os.SEEK_CUR)
  return s == b''

How to use this

while not is_eof(my_file):
    val = my_file.read(10)

Play with this code.


I use this function:

# Returns True if End-Of-File is reached
def EOF(f):
    current_pos = f.tell()
    file_size = os.fstat(f.fileno()).st_size
    return current_pos >= file_size

You can use below code snippet to read line by line, till end of file:

line = obj.readline()
while(line != ''):
    # Do Something
    line = obj.readline()

ReferenceURL : https://stackoverflow.com/questions/10140281/how-to-find-out-whether-a-file-is-at-its-eof

반응형