2017-02-02 6 views
1

https://docs.python.org/3/library/gzip.htmlPython 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 в дополнение к python-3.x? Я спрашиваю экспертов: это правда, что он упоминает python 3, но все еще python, некоторые люди, возможно, пропустили это ... Я думаю, что видел подобный случай, но я забыл, какой из них. – fedepad

ответ

3

Это означает, что r по умолчанию - rb, и если вы хотите текст, вы должны указать его, используя rt.

(в отличие от open поведения, где r означает rt, не rb)

+0

Я был _hoping_ именно так. Я был обеспокоен, что '' r'' был бинарным read_, и что '' rb'' был более двоичным, читал это '' r''. – jeff00seattle

2

Точно так, как вы говорите, и как уже покрыты @

Жан-Франсуа Фабр ответ.
Я просто хотел показать какой-то код, так как это было весело.
Давайте посмотрим на исходный код gzip.py в библиотеке python, чтобы убедиться, что это действительно то, что происходит.
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".
    Это мы можем увидеть в следующих строках:

    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 будет построен кастрированный баран есть дополнительные б или нет, как gz_mode может иметь b или нет на данный момент.
    Теперь класс class GzipFile(_compression.BaseStream) вызывается для построения binary_file.

В конструкторе следующие строки являются важными:

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') 

где можно ясно видеть, что если 'b' нет в режиме он будет добавлен

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

так что никакого различия между двумя режимами, как уже обсуждалось.

Смежные вопросы