python文件处理

查看内置函数open详细说明

help(open) 
dir(open)

 函数实现

  Open file and return a stream.  Raise IOError upon failure.

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

   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

  读写模式区别:

       r+  读完文件后从头部覆盖写入

       w+ 清空文件后写入

       a+  从尾部追加写入

       x+  新建文件后写入

 

查看文件详细说明

f = open('/xx/test.txt','r')
help(f)
dir(f)

 

文件常用方法

 

原文地址:https://www.cnblogs.com/xinzao/p/9026192.html