을 (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')
이미 설명한 두 가지 모드 사이의 차이는 없습니다.
사소한 궁금한 점 : python-3.x 외에도 python 태그를 여기에 적용해서는 안됩니까? 나는 전문가에게 물어 본다. 그것은 파이썬 3을 언급하지만 그것은 여전히 파이썬이다. 어떤 사람들은 그것을 놓쳤을지도 모른다. 나는 비슷한 케이스를 보았지만 어느 것을 잊어 버렸다고 생각한다. – fedepad