自学Python4.1-文件操做

自学Python之路-Python基础+模块+面向对象
自学Python之路-Python网络编程
自学Python之路-Python并发编程+数据库+前端
自学Python之路-django
html

自学Python4.1-文件操做

操做文件时,通常须要经历以下步骤:前端

  • 打开文件
  • 操做文件
  • 关闭文件(非必须)

1、打开文件

     open('文件路径', '模式')
     打开文件时,须要指定文件路径和以何等方式打开文件,打开后,便可获取该文件句柄,往后经过此文件句柄对该文件操做。打开文件的模式有:python

  • r ,只读模式【默认】
  • w,只写模式【不可读;不存在则建立;存在则清空内容;】
  • x, 只写模式【不可读;不存在则建立,存在则报错】
  • a, 追加模式【可读;   不存在则建立;存在则只追加内容;】

    "+" 表示能够同时读写某个文件数据库

  • r+, 读写【可读,可写】
  • w+,写读【可读,可写】
  • x+ ,写读【可读,可写】
  • a+, 写读【可读,可写】

     "b"表示以字节的方式操做django

  • rb  或 r+b
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b

    注:以b方式打开时,读取到的内容是字节类型,写入时也须要提供字节类型编程

模式 描述
r 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
rb 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。
r+ 打开一个文件用于读写。文件指针将会放在文件的开头。
rb+ 以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。
w 打开一个文件只用于写入。若是该文件已存在则将其覆盖。若是该文件不存在,建立新文件。
wb 以二进制格式打开一个文件只用于写入。若是该文件已存在则将其覆盖。若是该文件不存在,建立新文件。
w+ 打开一个文件用于读写。若是该文件已存在则将其覆盖。若是该文件不存在,建立新文件。
wb+ 以二进制格式打开一个文件用于读写。若是该文件已存在则将其覆盖。若是该文件不存在,建立新文件。
a 打开一个文件用于追加。若是该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容以后。若是该文件不存在,建立新文件进行写入。
ab 以二进制格式打开一个文件用于追加。若是该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容以后。若是该文件不存在,建立新文件进行写入。
a+ 打开一个文件用于读写。若是该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。若是该文件不存在,建立新文件用于读写。
ab+

以二进制格式打开一个文件用于追加。若是该文件已存在,文件指针将会放在文件的结尾。若是该文件不存在,建立新文件用于读写。网络

x
若是文件存在则报错,若是不存在,则建立文件并写内容

2、操做文件

class TextIOWrapper(_TextIOBase):
    """
    Character and line based layer over a BufferedIOBase object, buffer.
    
    encoding gives the name of the encoding that the stream will be
    decoded or encoded with. It defaults to locale.getpreferredencoding(False).
    
    errors determines the strictness of encoding and decoding (see
    help(codecs.Codec) or the documentation for codecs.register) and
    defaults to "strict".
    
    newline controls how line endings are handled. 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 line_buffering is True, a call to flush is implied when a call to
    write contains a newline character.
    """
    def close(self, *args, **kwargs): # real signature unknown
        关闭文件
        pass

    def fileno(self, *args, **kwargs): # real signature unknown
        文件描述符  
        pass

    def flush(self, *args, **kwargs): # real signature unknown
        刷新文件内部缓冲区
        pass

    def isatty(self, *args, **kwargs): # real signature unknown
        判断文件是不是赞成tty设备
        pass

    def read(self, *args, **kwargs): # real signature unknown
        读取指定字节数据
        pass

    def readable(self, *args, **kwargs): # real signature unknown
        是否可读
        pass

    def readline(self, *args, **kwargs): # real signature unknown
        仅读取一行数据
        pass

    def seek(self, *args, **kwargs): # real signature unknown
        指定文件中指针位置
        pass

    def seekable(self, *args, **kwargs): # real signature unknown
        指针是否可操做
        pass

    def tell(self, *args, **kwargs): # real signature unknown
        获取指针位置
        pass

    def truncate(self, *args, **kwargs): # real signature unknown
        截断数据,仅保留指定以前数据
        pass

    def writable(self, *args, **kwargs): # real signature unknown
        是否可写
        pass

    def write(self, *args, **kwargs): # real signature unknown
        写内容
        pass

    def __getstate__(self, *args, **kwargs): # real signature unknown
        pass

    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __next__(self, *args, **kwargs): # real signature unknown
        """ Implement next(self). """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    buffer = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    closed = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    encoding = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    errors = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    name = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    newlines = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
源码

 1. write(self, *args, **kwargs)  写数据并发

     read(self, *args, **kwargs)   读取指定字符数据app

f=open('test.log','w')
f.write('afaefafafafaf')   # 先写入文件
f.close()
f=open('test.log','r')
ret=f.read(6)   # 读取6个字符
f.close()
print(ret)

输出 afafae
2. readline(self, *args, **kwargs)  仅读取一行

3. tell(self, *args, **kwargs) 获取指针位置(按字节)
4. seek(self, *args, **kwargs)  指定文件中指针位置
5. truncate(self, *args, **kwargs)  截断数据,仅保留指定以前数据,更新原文件 ide

3、 关闭文件

这步操做并非必须的,若是使用open()函数打开文件,那么要记得最终close()文件

若是使用with 语句打开的文件,则不须要。在with 语句主体语句执行完以后,会自动调用close()来关闭文件句柄。语法以下:

with open('db1', 'r', encoding="utf-8") as f1:
    for line in f1:
     print(line)

同时打开两个文件,以下:

with open('file1', 'r', encoding="utf-8") as f1, open("file2", 'w',encoding="utf-8") as f2:
    pass
相关文章
相关标签/搜索