python3 文件操作

 

def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open
    """
    Open file and return a stream.  Raise IOError 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, '', '
', '
', and '
'.  It works as
    follows:
    
    * On input, if newline is None, universal newlines mode is
      enabled. Lines in the input can end in '
', '
', or '
', and
      these are translated into '
' 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 '
' characters written are
      translated to the system default line separator, os.linesep. If
      newline is '' or '
', no translation takes place. If newline is any
      of the other legal values, any '
' 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.
    """

Google机翻

def open(file,mode ='r',buffering = None,encoding = None,errors = None,newline = None,closefd = True):#known open case of open
    “””
    打开文件并返回一个流。失败时引发IOError。
    
    file是文本或字节字符串,给出名称(和路径
    如果文件不在当前工作目录中)
    打开或文件的整数文件描述符
    包裹。 (如果给出了文件描述符,则在关闭时将关闭
    返回的I / O对象已关闭,除非将closefd设置为False。)
    
    mode是一个可选字符串,用于指定文件的模式
    打开了。它默认为'r',表示打开文本阅读
    模式。其他常见值是'w'用于写入(截断文件,如果
    它已经存在),'x'用于创建和写入新文件,和
    'a'用于追加(在某些Unix系统上,意味着所有写入
    无论当前的搜索位置如何,都附加到文件的末尾。
    在文本模式下,如果未指定编码,则使用的编码是平台
    dependent:locale.getpreferredencoding(False)被调用来获取
    当前的语言环境编码。 (对于读写原始字节,请使用二进制
    模式和保留编码未指定。)可用的模式是:
    
    ========= ========================================= ======================
    字符含义
    --------- ----------------------------------------- ----------------------
    'r'开放阅读(默认)
    'w'打开写入,先截断文件
    'x'创建一个新文件并打开它进行写入
    'a'打开写入,如果存在则附加到文件的末尾
    'b'二进制模式
    't'文字模式(默认)
    '+'打开磁盘文件进行更新(读写)
    'U'通用换行模式(已弃用)
    ========= ========================================= ======================
    
    默认模式为“rt”(打开以读取文本)。对于二进制随机
    访问时,模式'w + b'打开并将文件截断为0字节,而
    'r + b'打开文件而不截断。 'x'模式暗示'w'和
    如果文件已存在,则引发`FileExistsError`。
    
    Python区分以二进制和文本模式打开的文件,
    即使底层操作系统没有。打开的文件
    二进制模式(将'b'附加到mode参数)返回内容为
    bytes对象没有任何解码。在文本模式下(默认,或者
    't'被附加到mode参数),文件的内容是
    以字符串形式返回,首先使用a解码字节
    依赖于平台的编码或使用指定的编码(如果给定)。
    
    “U”模式已弃用,将在未来版本中引发异常
    Python它在Python 3中没有效果。使用换行来控制
    通用换行模式。
    
    buffering是一个可选的整数,用于设置缓冲策略。
    传递0切换缓冲关闭(仅允许在二进制模式下),1选择
    行缓冲(仅在文本模式下可用),并且整数> 1表示
    固定大小的块缓冲区的大小。没有缓冲参数时
    给定,默认缓冲策略的工作方式如下:
    
    *二进制文件以固定大小的块缓冲;缓冲区的大小
      选择使用启发式试图确定底层设备
      “块大小”并回落到`io.DEFAULT_BUFFER_SIZE`。
      在许多系统上,缓冲区通常为4096或8192字节长。
    
    *“交互式”文本文件(isatty()返回True的文件)
      使用线缓冲。其他文本文件使用上述策略
      用于二进制文件。
    
    encoding是用于解码或编码的编码的名称
    文件。这应该只在文本模式下使用。默认编码是
    平台依赖,但Python支持的任何编码都可以
    通过。有关支持的编码列表,请参阅编解码器模块。
    
    errors是一个可选字符串,用于指定编码错误的方式
    被处理---这个参数不应该用于二进制模式。通过
    如果存在编码错误,则“严格”引发ValueError异常
    (默认值为None具有相同的效果),或者将“忽略”传递给忽略
    错误。 (请注意,忽略编码错误可能会导致数据丢失。)
    请参阅codecs.register的文档或运行'help(codecs.Codec)'
    获取允许的编码错误字符串列表。
    
    换行符控制通用换行符的工作方式(仅适用于文本
    模式)。它可以是None,''' n'' r'' r  n'。它起作用
    如下:
    
    *输入时,如果换行为无,则通用换行模式为
      启用。输入中的行可以以' n'' r'' r  n'结尾,以及
      在返回之前,这些被翻译成' n'
      呼叫者。如果是'',则启用通用换行模式,但行
View Code

菜鸟教程-----https://www.runoob.com/python3/python3-file-seek.html

Python3 File(文件) 方法

open() 方法

Python open() 方法用于打开一个文件,并返回文件对象,在对文件进行处理过程都需要使用到这个函数,如果该文件无法被打开,会抛出 OSError。

注意:使用 open() 方法一定要保证关闭文件对象,即调用 close() 方法。

open() 函数常用形式是接收两个参数:文件名(file)和模式(mode)。

open(file, mode='r')

完整的语法格式为:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

参数说明:

  • file: 必需,文件路径(相对或者绝对路径)。
  • mode: 可选,文件打开模式
  • buffering: 设置缓冲
  • encoding: 一般使用utf8
  • errors: 报错级别
  • newline: 区分换行符
  • closefd: 传入的file参数类型
  • opener:

mode 参数有:

模式描述
t 文本模式 (默认)。
x 写模式,新建一个文件,如果该文件已存在则会报错。
b 二进制模式。
+ 打开一个文件进行更新(可读可写)。
U 通用换行模式(Python 3 不支持)。
r 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
rb 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。一般用于非文本文件如图片等。
r+ 打开一个文件用于读写。文件指针将会放在文件的开头。
rb+ 以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。一般用于非文本文件如图片等。
w 打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
wb 以二进制格式打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。一般用于非文本文件如图片等。
w+ 打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
wb+ 以二进制格式打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。一般用于非文本文件如图片等。
a 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
ab 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
a+ 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。
ab+ 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。

默认为文本模式,如果要以二进制模式打开,加上 b 。

file 对象

file 对象使用 open 函数来创建,下表列出了 file 对象常用的函数:

序号方法及描述
1

file.close()

关闭文件。关闭后文件不能再进行读写操作。

2

file.flush()

刷新文件内部缓冲,直接把内部缓冲区的数据立刻写入文件, 而不是被动的等待输出缓冲区写入。

3

file.fileno()

返回一个整型的文件描述符(file descriptor FD 整型), 可以用在如os模块的read方法等一些底层操作上。

4

file.isatty()

如果文件连接到一个终端设备返回 True,否则返回 False。

5

file.next()

Python 3 中的 File 对象不支持 next() 方法。

返回文件下一行。

6

file.read([size])

从文件读取指定的字节数,如果未给定或为负则读取所有。

7

file.readline([size])

读取整行,包括 " " 字符。

8

file.readlines([sizeint])

读取所有行并返回列表,若给定sizeint>0,返回总和大约为sizeint字节的行, 实际读取值可能比 sizeint 较大, 因为需要填充缓冲区。

9

file.seek(offset[, whence])

设置文件当前位置

10

file.tell()

返回文件当前位置。

11

file.truncate([size])

从文件的首行首字符开始截断,截断文件为 size 个字符,无 size 表示从当前位置截断;截断之后后面的所有字符被删除,其中 Widnows 系统下的换行代表2个字符大小。

12

file.write(str)

将字符串写入文件,返回的是写入的字符长度。

13

file.writelines(sequence)

向文件写入一个序列字符串列表,如果需要换行则要自己加入每行的换行符。

原文地址:https://www.cnblogs.com/DirWang/p/11436603.html