python之open()和os.open()的区分

权浩邈
2023-12-01

        这两天在使用Python的时候想使用open来打开一个文件。由于自己不清楚内建的open()和os模块的open()的区别。在项目中错用了os.open()当成了内建的open()使用,导致一直提示文件找不到。下面详细说说这两者的差异。

1、built-in  open()使用

def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True):
    """
    Open file and return a stream.  Raise OSError upon failure.
    
    file is either a text or byte string giving the name (and the path
    if the file isn't in the current working directory) of the file to
    be opened or an integer file descriptor of the file to be
    wrapped. (If a file descriptor is given, it is closed when the
    returned I/O object is closed, unless closefd is set to False.)
    
    mode is an optional string that specifies the mode in which the file
    is opened. It defaults to 'r' which means open for reading in text
    mode.  Other common values are 'w' for writing (truncating the file if
    it already exists), 'x' for creating and writing to a new file, and
    'a' for appending (which on some Unix systems, means that all writes
    append to the end of the file regardless of the current seek position).
    In text mode, if encoding is not specified the encoding used is platform
    dependent: locale.getpreferredencoding(False) is called to get the
    current locale encoding. (For reading and writing raw bytes use binary
    mode and leave encoding unspecified.) The available modes are:
    
    ========= ===============================================================
    Character Meaning
    --------- ---------------------------------------------------------------
    'r'       open for reading (default)
    'w'       open for writing, truncating the file first
    'x'       create a new file and open it for writing
    'a'       open for writing, appending to the end of the file if it exists
    'b'       binary mode
    't'       text mode (default)
    '+'       open a disk file for updating (reading and writing)
    'U'       universal newline mode (deprecated)
    ========= ===============================================================
    
    The default mode is 'rt' (open for reading text). For binary random
    access, the mode 'w+b' opens and truncates the file to 0 bytes, while
    'r+b' opens the file without truncation. The 'x' mode implies 'w' and
    raises an `FileExistsError` if the file already exists.
    
    Python distinguishes between files opened in binary and text modes,
    even when the underlying operating system doesn't. Files opened in
    binary mode (appending 'b' to the mode argument) return contents as
    bytes objects without any decoding. In text mode (the default, or when
    't' is appended to the mode argument), the contents of the file are
    returned as strings, the bytes having been first decoded using a
    platform-dependent encoding or using the specified encoding if given.
    
    'U' mode is deprecated and will raise an exception in future versions
    of Python.  It has no effect in Python 3.  Use newline to control
    universal newlines mode.
    
    buffering is an optional integer used to set the buffering policy.
    Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
    line buffering (only usable in text mode), and an integer > 1 to indicate
    the size of a fixed-size chunk buffer.  When no buffering argument is
    given, the default buffering policy works as follows:
    
    * Binary files are buffered in fixed-size chunks; the size of the buffer
      is chosen using a heuristic trying to determine the underlying device's
      "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
      On many systems, the buffer will typically be 4096 or 8192 bytes long.
    
    * "Interactive" text files (files for which isatty() returns True)
      use line buffering.  Other text files use the policy described above
      for binary files.
    
    encoding is the name of the encoding used to decode or encode the
    file. This should only be used in text mode. The default encoding is
    platform dependent, but any encoding supported by Python can be
    passed.  See the codecs module for the list of supported encodings.
    
    errors is an optional string that specifies how encoding errors are to
    be handled---this argument should not be used in binary mode. Pass
    'strict' to raise a ValueError exception if there is an encoding error
    (the default of None has the same effect), or pass 'ignore' to ignore
    errors. (Note that ignoring encoding errors can lead to data loss.)
    See the documentation for codecs.register or run 'help(codecs.Codec)'
    for a list of the permitted encoding error strings.
    
    newline controls how universal newlines works (it only applies to text
    mode). It can be None, '', '\n', '\r', and '\r\n'.  It works as
    follows:
    
    * On input, if newline is None, universal newlines mode is
      enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
      these are translated into '\n' before being returned to the
      caller. If it is '', universal newline mode is enabled, but line
      endings are returned to the caller untranslated. If it has any of
      the other legal values, input lines are only terminated by the given
      string, and the line ending is returned to the caller untranslated.
    
    * On output, if newline is None, any '\n' characters written are
      translated to the system default line separator, os.linesep. If
      newline is '' or '\n', no translation takes place. If newline is any
      of the other legal values, any '\n' characters written are translated
      to the given string.
    
    If closefd is False, the underlying file descriptor will be kept open
    when the file is closed. This does not work when a file name is given
    and must be True in that case.
    
    A custom opener can be used by passing a callable as *opener*. The
    underlying file descriptor for the file object is then obtained by
    calling *opener* with (*file*, *flags*). *opener* must return an open
    file descriptor (passing os.open as *opener* results in functionality
    similar to passing None).
    
    open() returns a file object whose type depends on the mode, and
    through which the standard file operations such as reading and writing
    are performed. When open() is used to open a file in a text mode ('w',
    'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
    a file in a binary mode, the returned class varies: in read binary
    mode, it returns a BufferedReader; in write binary and append binary
    modes, it returns a BufferedWriter, and in read/write mode, it returns
    a BufferedRandom.
    
    It is also possible to use a string or bytearray as a file for both
    reading and writing. For strings StringIO can be used like a file
    opened in a text mode, and for bytes a BytesIO can be used like a file
    opened in a binary mode.
    """

翻译成中文如下

        打开文件并返回一个流对象。失败时会抛出OSError。

        被打开的给定名称或文件路径(文件不在当前目录的情况下)的文件可以是字符或字节型字符串,或是被封装的整型文件描述符,如果给定了文件描述符,当返回的I/O对象被关闭了,文件描述符也被关闭了,除非设置了closedfd=False.

        模式是可选字符串,用来指定以何种模式打开的文件。

mode默认值为'r'代表以读方式打开文件;

其他通用的值如‘w’代表以写方式(如果文件已经存在则截断文件);

'x'代表创建并写入到新文件中,并且'a'代表追加到文件中;

        在文本模式中,如果没有指定编码方式,则编码方式通常依赖平台:调用locale.getpreferredencoding(False)获取当前本地编码方式。

        对于正在读或写入原生字节使用二进制模式,并且保留未指定的编码。可用的模式包括:

'r'       读方式打开文件(默认)
'w'       先截断文件,然后以写方式打开文件
'x'       创建新文件并以写方式打开文件
'a'       以写方式打开文件,如果文件已存在则追加内容到文件末尾
'b'       二进制方式
't'       字符模式 (默认)
'+'       打开磁盘文件用于更新(兼顾读和写模式)
'U'       通用换行模式(已废弃)

        默认的模式为"rt" (打开读文件)。

        对于二进制随机访问,模式为'w+b',打开并将文件截断为0字节;而'r+b' 代表打开文件但不会截断文件。      

        'x'模式暗含‘w’并且如果文件已存在会抛出FileExistsError错误。

        即使底层操作系统不区分二进制或文件文件,python也区分以二进制和文本模式打开的文件。以二进制模式打开的文件(追加了'b'到模式参数中)返回的内容是没有经过任何编码的字节对象;以字符模式(默认的,或追加了't'到模式参数中),字节都已经被平台依赖的编码方式或给定的指定编码方式解码了,返回的文件内容是字符串。       

        encoding指的是编码方式的名称,被用来解码或编码文件。它只能被使用到字符模式中。默认的编码方式是平台依赖的,但是可以传入任何python支持的编码方式。

        newline用来控制通用换行符如何工作(它仅能用于字符模式中)。它可以为None, '', '\n', '\r'和‘\r\n’。它工作遵循如下规则:       

对于读取:
        当newline为None时,会启用通用换行模式,输入中的'\n'(linux系统换行符),'\r'(mac换行符),'\r\n'(windows换行符)都会被转换成'\n'。
当newline为''时,同样会启用通用换行模式,三种换行符都会被当作换行符且原模原样的返回给你,不会被转换。
当newline为5种里面的其他选项时,仅把对应的换行符作为换行符并进行返回。

对于输出:
        当newline为None时,所有'\n'会被转换成系统默认的换行符。所以比如windows下写入一行末尾加上'\r\n',实际上会变成'\r\r\n'
当newline为'''\n'时,不进行转换。
当newline为其他选项时,'\n'会被转换成对应的换行符。

        如果closefd=False,当文件被关闭了,底层的文件描述符将保持打开。当给定的文件名时,这将不起作用,并且在这种情况下closefd必须为True。

2、os.open()使用

        Python中的OS模块提供了与操作系统进行交互的函数。操作系统属于Python的标准实用程序模块。该模块提供了使用依赖于操作系统的函数的便携式方法。

   os.open()Python中的方法用于打开指定的文件路径,并根据指定的标志及其模式根据指定的模式设置各种标志。
        此方法返回新打开文件的文件描述符。返回的文件描述符是不可继承的。

用法: os.open(path, flags, mode = 0o777, *, dir_fd = None)

参数:
        Path:代表文件系统路径的path-like对象。这是要打开的文件路径。
        path-like对象是表示路径的字符串或字节对象。
        flags:此参数指定要为新打开的文件设置的标志。
        mode(可选):代表新打开文件模式的数值。该参数的默认值为0o777(八进制)。
        dir_fd(可选):引用目录的文件描述符。

        返回类型:此方法返回新打开文件的文件描述符。

  • flags -- 该参数可以是以下选项,多个使用 "|" 隔开:

    • os.O_RDONLY: 以只读的方式打开
    • os.O_WRONLY: 以只写的方式打开
    • os.O_RDWR : 以读写的方式打开
    • os.O_NONBLOCK: 打开时不阻塞
    • os.O_APPEND: 以追加的方式打开
    • os.O_CREAT: 创建并打开一个新文件
    • os.O_TRUNC: 打开一个文件并截断它的长度为零(必须有写权限)
    • os.O_EXCL: 如果指定的文件存在,返回错误
    • os.O_SHLOCK: 自动获取共享锁
    • os.O_EXLOCK: 自动获取独立锁
    • os.O_DIRECT: 消除或减少缓存效果
    • os.O_FSYNC : 同步写入
    • os.O_NOFOLLOW: 不追踪软链接
#!/usr/bin/python3
  
import os, sys

# 打开文件
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# 写入字符串
os.write(fd, str.encode("This is test"))

# 关闭文件
os.close( fd )

print ("关闭文件成功!!")

 类似资料: