2017-02-02 4 views
1

https://docs.python.org/3/library/gzip.html파이썬 3 : gzip.open() 및 모드

나는 gzip.open()를 사용하는 것을 고려하고있다, 그리고 나는 mode 인수에 대해 조금 혼란 스러워요 :

모드 인수 중 하나 일 수 있습니다 ' 바이너리 모드의 경우 'r', 'rb', 'a', 'ab', 'w', 'wb', 'x' 또는 'xb'또는 'rt', 'at', 'wt' 텍스트 모드의 경우 'xt' 기본값은 'rb'입니다.

'w''wb'의 차이점은 무엇입니까?

문서에는 모두 바이너리 모드입니다.

그렇다면 'w''wb' 사이에는 차이가 없음을 의미합니까?

+0

사소한 궁금한 점 : python-3.x 외에도 python 태그를 여기에 적용해서는 안됩니까? 나는 전문가에게 물어 본다. 그것은 파이썬 3을 언급하지만 그것은 여전히 ​​파이썬이다. 어떤 사람들은 그것을 놓쳤을지도 모른다. 나는 비슷한 케이스를 보았지만 어느 것을 잊어 버렸다고 생각한다. – fedepad

답변

3

즉, 의 기본값은 rb이며, 텍스트를 원할 경우 rt을 사용해야합니다.

당신이 말한대로 정확히

+0

나는 그랬다. 나는''r''이 바이너리 read_이고''rb''''가 바이너리 read_''' r''' 였다고 걱정했습니다. – jeff00seattle

2

을 (r하지 rb, rt 의미 어디 open 행동에 반대) 및 이미 @으로

장 - 프랑수아 파브르의 대답에 덮여있다.
재미 있었으므로 코드를 보여주고 싶었습니다.
파이썬 라이브러리에있는 gzip.py 소스 코드를 살펴보면 실제로 어떻게되는지 알 수 있습니다.
gzip.open()https://github.com/python/cpython/blob/master/Lib/gzip.py 여기에서 찾을 수 있습니다 나는 우리가 알

def open(filename, mode="rb", compresslevel=9, 
     encoding=None, errors=None, newline=None): 
    """Open a gzip-compressed file in binary or text mode. 
    The filename argument can be an actual filename (a str or bytes object), or 
    an existing file object to read from or write to. 
    The mode argument can be "r", "rb", "w", "wb", "x", "xb", "a" or "ab" for 
    binary mode, or "rt", "wt", "xt" or "at" for text mode. The default mode is 
    "rb", and the default compresslevel is 9. 
    For binary mode, this function is equivalent to the GzipFile constructor: 
    GzipFile(filename, mode, compresslevel). In this case, the encoding, errors 
    and newline arguments must not be provided. 
    For text mode, a GzipFile object is created, and wrapped in an 
    io.TextIOWrapper instance with the specified encoding, error handling 
    behavior, and line ending(s). 
    """ 
    if "t" in mode: 
     if "b" in mode: 
      raise ValueError("Invalid mode: %r" % (mode,)) 
    else: 
     if encoding is not None: 
      raise ValueError("Argument 'encoding' not supported in binary mode") 
     if errors is not None: 
      raise ValueError("Argument 'errors' not supported in binary mode") 
     if newline is not None: 
      raise ValueError("Argument 'newline' not supported in binary mode") 

    gz_mode = mode.replace("t", "") 
    if isinstance(filename, (str, bytes, os.PathLike)): 
     binary_file = GzipFile(filename, gz_mode, compresslevel) 
    elif hasattr(filename, "read") or hasattr(filename, "write"): 
     binary_file = GzipFile(None, gz_mode, compresslevel, filename) 
    else: 
     raise TypeError("filename must be a str or bytes object, or a file") 

    if "t" in mode: 
     return io.TextIOWrapper(binary_file, encoding, errors, newline) 
    else: 
     return binary_file 

몇 가지 아래에보고 :

  • 기본 모드는 신고 문서로 rb이다는
  • 바이너리를 열 말한다 예를 들어 파일이 "r", "rb", "w", "wb"인지는 상관하지 않습니다.
    이것은 우리가 다음 줄에 볼 수 있습니다 추가 B 여부를 gz_mode이 시점에서 b 여부를 가질 수를 거기 어떠했는지

    gz_mode = mode.replace("t", "") 
    if isinstance(filename, (str, bytes, os.PathLike)): 
        binary_file = GzipFile(filename, gz_mode, compresslevel) 
    elif hasattr(filename, "read") or hasattr(filename, "write"): 
        binary_file = GzipFile(None, gz_mode, compresslevel, filename) 
    else: 
        raise TypeError("filename must be a str or bytes object, or a file") 
    
    if "t" in mode: 
        return io.TextIOWrapper(binary_file, encoding, errors, newline) 
    else: 
        return binary_file 
    

    은 기본적으로 이진 파일 binary_file 내장됩니다.
    이제 class GzipFile(_compression.BaseStream) 클래스를 호출하여 binary_file을 빌드합니다.

생성자에서 다음 줄이 중요하다

명확 경우 'b' 그렇게있다가

if mode and 'b' not in mode: 
      mode += 'b' 

추가됩니다 모드에 존재하지 않는 것을 알 수있다

if mode and ('t' in mode or 'U' in mode): 
     raise ValueError("Invalid mode: {!r}".format(mode)) 
    if mode and 'b' not in mode: 
     mode += 'b' 
    if fileobj is None: 
     fileobj = self.myfileobj = builtins.open(filename, mode or 'rb') 
    if filename is None: 
     filename = getattr(fileobj, 'name', '') 
     if not isinstance(filename, (str, bytes)): 
      filename = '' 
    else: 
     filename = os.fspath(filename) 
    if mode is None: 
     mode = getattr(fileobj, 'mode', 'rb') 

이미 설명한 두 가지 모드 사이의 차이는 없습니다.