天天看點

自學Python4.1-檔案操作

自學Python之路-Python基礎+子產品+面向對象

自學Python之路-Python網絡程式設計

自學Python之路-Python并發程式設計+資料庫+前端

自學Python之路-django

自學Python4.1-檔案操作

操作檔案時,一般需要經曆如下步驟:

  • 打開檔案
  • 操作檔案
  • 關閉檔案(非必須)

一、打開檔案

open('檔案路徑', '模式')

     打開檔案時,需要指定檔案路徑和以何等方式打開檔案,打開後,即可擷取該檔案句柄,日後通過此檔案句柄對該檔案操作。打開檔案的模式有:

  • r ,隻讀模式【預設】
  • w,隻寫模式【不可讀;不存在則建立;存在則清空内容;】
  • x, 隻寫模式【不可讀;不存在則建立,存在則報錯】
  • a, 追加模式【可讀;   不存在則建立;存在則隻追加内容;】

    "+" 表示可以同時讀寫某個檔案

  • r+, 讀寫【可讀,可寫】
  • w+,寫讀【可讀,可寫】
  • x+ ,寫讀【可讀,可寫】
  • a+, 寫讀【可讀,可寫】

     "b"表示以位元組的方式操作

  • 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
如果檔案存在則報錯,如果不存在,則建立檔案并寫内容      

二、操作檔案

自學Python4.1-檔案操作
自學Python4.1-檔案操作
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)   讀取指定字元資料

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)  截斷資料,僅保留指定之前資料,更新原檔案 

三、 關閉檔案

這步操作并不是必須的,如果使用open()函數打開檔案,那麼要記得最終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