Python: open().read()->str , 하지만 대용량 파일용
파일을 서버에 POST해야 하는 사용 사례가 있었습니다.
requests로 게시하기 위한 순진한 구현은 다음과 같습니다.with open("my_file.bin", 'rb') as fh:
    requests.post(url, data={"bytes": fh.read()})
작업 완료! 잘. 파일이 정말 큰 경우 해당
.read() 작업은 로드된 바이트를 requests.post(...)에 전달하기 전에 전체 파일을 메모리에 로드하려고 시도합니다.분명히 이것은 아플 것입니다. 많이.
mmap 사용
빠른 검색yielded a solution은
mmap를 사용하여 "메모리 매핑된"개체를 생성합니다. 이 개체는 문자열처럼 작동하는 동시에 필요에 따라 청크로만 읽히는 파일에 의해 지원됩니다.늘 그렇듯이 저는 물건을 재사용 가능하고 삽입하기 쉽게 만드는 것을 좋아합니다.
open()에 대한 일반 호출 대신 사용할 수 있는 컨텍스트 개체에 예제를 적용했습니다.# It's a tiny snippet, but go on.
# Delviered to You under MIT Expat License, aka "Do what you want"
# I'm not even fussy about attribution.
import mmap
class StringyFileReader:
    def __init__(self, file_name, mode):
        if mode not in ("r", "rb"):
            raise ValueError(f"Invalid mode '{mode}'. Only read-modes are supported")
        self._fh = open(file_name, mode)
        # A file size of 0 means "whatever the size of the file actually is" on non-Windows
        # On Windows, you'll need to obtain the actual size, though
        fsize = 0
        self._mmap = mmap.mmap(self._fh.fileno(), fsize, access=mmap.ACCESS_READ)
    def __enter__(self):
        return self
    def read(self):
        return self._mmap
    def __exit__(self, *args):
        self._mmap.close()
        self._fh.close()
그런 다음 원래 순진한 예제를 다음과 같이 간단하게 조정할 수 있습니다.
with StringyFileReader("my_file.bin", 'rb') as fh:
    requests.post(url, data={"bytes": fh.read()})
직업. 완료.
Reference
이 문제에 관하여(Python: open().read()->str , 하지만 대용량 파일용), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/taikedz/python-openread-str-but-for-big-files-1d15텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)