Python open(name, mode)函数文件打开模式介绍

open(name, mode)函数文件打开模式

在Python中使用open()函数打开文件时,需要指定打开模式。模式标识了文件对象是以何种方式被打开和操作的。下面是可用的文件打开模式:

  • r:只读模式,文件指针指向文件开头。
  • r+:读写模式,文件指针指向文件开头。
  • w:只写模式,文件指针指向文件开头。如果文件已经存在,则其内容将被截断,即清空文件;如果文件不存在,则会创建它。
  • w+:读写模式,文件指针指向文件开头。如果文件已经存在,则其内容将被截断,即清空文件;如果文件不存在,则会创建它。
  • a:只写模式,文件指针指向文件末尾。如果文件已经存在,则程序会从文件末尾开始写入;如果文件不存在,则会创建它。
  • a+:读写模式,文件指针指向文件末尾。如果文件已经存在,则程序会从文件末尾开始写入;如果文件不存在,则会创建它。

另外,还有一些可选的访问模式:

  • t:文本模式,用于打开文本文件,默认模式。
  • b:二进制模式,用于打开二进制文件。
  • x:新建文件,如果文件已经存在则会抛出异常。

模式可以以二进制或者文本方式打开文件,可以同时使用rb或者rt进行指定。例如:wb以二进制可写方式打开文件,rt以文本可读方式打开文件。

open()函数源码:
def open(name, mode=None, buffering=None): # real signature unknown; restored from __doc__
    """
    open(name[, mode[, buffering]]) -> file object
    
    Open a file using the file() type, returns a file object.  This is the
    preferred way to open a file.  See file.__doc__ for further information.
    """
    return file('/dev/null')
sftp.open():
    def open(self, filename, mode="r", bufsize=-1):
        """
        Open a file on the remote server.  The arguments are the same as for
        Python's built-in `python:file` (aka `python:open`).  A file-like
        object is returned, which closely mimics the behavior of a normal
        Python file object, including the ability to be used as a context
        manager.

        The mode indicates how the file is to be opened: ``'r'`` for reading,
        ``'w'`` for writing (truncating an existing file), ``'a'`` for
        appending, ``'r+'`` for reading/writing, ``'w+'`` for reading/writing
        (truncating an existing file), ``'a+'`` for reading/appending.  The
        Python ``'b'`` flag is ignored, since SSH treats all files as binary.
        The ``'U'`` flag is supported in a compatible way.

        Since 1.5.2, an ``'x'`` flag indicates that the operation should only
        succeed if the file was created and did not previously exist.  This has
        no direct mapping to Python's file flags, but is commonly known as the
        ``O_EXCL`` flag in posix.

        The file will be buffered in standard Python style by default, but
        can be altered with the ``bufsize`` parameter.  ``<=0`` turns off
        buffering, ``1`` uses line buffering, and any number greater than 1
        (``>1``) uses that specific buffer size.

        :param str filename: name of the file to open
        :param str mode: mode (Python-style) to open in
        :param int bufsize: desired buffering (default: ``-1``)
        :return: an `.SFTPFile` object representing the open file

        :raises: ``IOError`` -- if the file could not be opened.
        """
        filename = self._adjust_cwd(filename)
        self._log(DEBUG, "open({!r}, {!r})".format(filename, mode))
        imode = 0
        if ("r" in mode) or ("+" in mode):
            imode |= SFTP_FLAG_READ
        if ("w" in mode) or ("+" in mode) or ("a" in mode):
            imode |= SFTP_FLAG_WRITE
        if "w" in mode:
            imode |= SFTP_FLAG_CREATE | SFTP_FLAG_TRUNC
        if "a" in mode:
            imode |= SFTP_FLAG_CREATE | SFTP_FLAG_APPEND
        if "x" in mode:
            imode |= SFTP_FLAG_CREATE | SFTP_FLAG_EXCL
        attrblock = SFTPAttributes()
        t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
        if t != CMD_HANDLE:
            raise SFTPError("Expected handle")
        handle = msg.get_binary()
        self._log(
            DEBUG,
            "open({!r}, {!r}) -> {}".format(
                filename, mode, u(hexlify(handle))
            ),
        )
        return SFTPFile(self, handle, mode, bufsize)
open()函数常用使用方法
只写二进制模式
with open(local_path, 'wb') as f:
只读二进制模式
with open(local_path, 'rb') as f:
读写二进制模式,只读二进制模式
# open both local and remote file
local_file = open(local_path, "r+b")
remote_file = sftp.open(remote_path, "rb")

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值