檔案操作(初階)

morra發表於2016-10-16

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

  • 開啟檔案
  • 操作檔案
  • 關閉檔案
#open()是python的內建函式,而read()、close()等都是屬於TextIOWrapper類的,詳情參見原始碼。

f = open('1.txt', 'r')       #開啟檔案
data = f.read()           #操作檔案
f.close()                #關閉檔案
print(data)

一、開啟檔案

檔案在open的時候是不會被加到記憶體中的,只有read或write的時候才會加到記憶體中。

開啟檔案的模式有:

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

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

r+, 讀寫【可讀,可寫】,從開始向後讀,寫和追加的時候指標會調到最後
w+,寫讀【可讀,可寫】,先清空資料,從開始向後讀,寫和追加的時候指標會調到最後
x+ ,寫讀【可讀,可寫】,同上
a+, 寫讀【可讀,可寫】,同上

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

rb 或 r+b
wb 或 w+b
xb 或 w+b
ab 或 a+b
注:以b方式開啟時,讀取到的內容是位元組型別,寫入時也需要提供位元組型別

二、操作檔案

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): 
        """關閉檔案"""      
        pass

    def detach(self, *args, **kwargs): 
        pass

    def fileno(self, *args, **kwargs): 
        """檔案描述符"""  
        pass

    def flush(self, *args, **kwargs): 
        """把緩衝區的內容寫入硬碟"""
        pass

    def isatty(self, *args, **kwargs): 
        pass

    def read(self, *args, **kwargs): 
        """讀取指定位元組資料"""
        pass

    def readable(self, *args, **kwargs): 
        pass

    def readline(self, *args, **kwargs): 
        """只讀取一行資料"""
        pass

    def seek(self, *args, **kwargs): 
        """
        指定檔案中指標位置
        f.seek(0) 把指標歸零
        """
        pass

    def seekable(self, *args, **kwargs): 
        pass

    def tell(self, *args, **kwargs): 
        """獲取當前指標位置"""
        pass

    def truncate(self, *args, **kwargs): 
        pass

    def writable(self, *args, **kwargs): 
        pass

    def write(self, *args, **kwargs): 
        pass

    def __getstate__(self, *args, **kwargs): 
        pass

    def __init__(self, *args, **kwargs): 
        pass

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

    def __next__(self, *args, **kwargs): 
        """ Implement next(self). """
        pass

    def __repr__(self, *args, **kwargs): 
        """ Return repr(self). """
        pass

三、關閉檔案

使用open開啟檔案後一定要記得呼叫檔案物件的close()方法。比如可以用try/finally語句來確保最後能關閉檔案。


file_object = open('thefile.txt')
try:
     all_the_text = file_object.read( )
finally:
     file_object.close( )

注:不能把open語句放在try塊裡,因為當開啟檔案出現異常時,檔案物件file_object無法執行close()方法。

四、程式碼塊

建立程式碼塊能實現的功能:

1、每次操作完後不用再次手動關閉

2、能同時開啟兩個檔案(2.7之後才有的功能)

批量操作


with open('1.txt', 'r') as f1, open('2.txt','r') as f2:
    pass

模擬檔案複製的過程(針對大檔案比較有效)


with open('1.txt', 'r') as f1, open('2.txt','w') as f2:
    for line in f1:         #讀取原檔案內容,然後一行一行寫到新檔案中
        f2.write(line)