Python學習16:open內置函數全方面講解

筆者: 出處:https://blog.csdn.net/JackMengJin 筆者原創,文章轉載需註明,如果喜歡請點贊+關注,感謝支持!

函數學習接近尾聲,這次主要帶來open內置函數的全方面講解。

open函數的官方資料:https://docs.python.org/zh-cn/3.7/library/functions.html#open


 

目錄

open內置函數全方面講解

1.open函數基礎內容

1.1 定義

1.2 open函數的參數組成

1.3 open函數參數的作用

1.4 mode模式所有參數用法

1.5 x原創模式

1.6 對於文件讀取的深入理解

1.7 文件操作的流程

2.open函數的實戰應用

2.1 普通操作

2.2上下文表達式

2.3 read()和readline()區別

 

 


open內置函數全方面講解

open函數在前面內置函數的學習中一筆帶過,是因爲在後面的學習中open函數非常重要,單獨拿出來作爲一個專題講比較好。

先看下python官網對open函數的隆重介紹


open(filemode='r'buffering=-1encoding=Noneerrors=Nonenewline=Noneclosefd=Trueopener=None)

打開 file 並返回對應的 file object。如果該文件不能打開,則觸發 OSError

file 是一個 path-like object,表示將要打開的文件的路徑(絕對路徑或者當前工作目錄的相對路徑),也可以是要被封裝的整數類型文件描述符。(如果是文件描述符,它會隨着返回的 I/O 對象關閉而關閉,除非 closefd 被設爲 False 。)

mode 是一個可選字符串,用於指定打開文件的模式。默認值是 'r' ,這意味着它以文本模式打開並讀取。其他常見模式有:寫入 'w' (截斷已經存在的文件);排它性創建 'x' ;追加寫 'a' (在 一些 Unix 系統上,無論當前的文件指針在什麼位置,所有 寫入都會追加到文件末尾)。在文本模式,如果 encoding 沒有指定,則根據平臺來決定使用的編碼:使用 locale.getpreferredencoding(False) 來獲取本地編碼。(要讀取和寫入原始字節,請使用二進制模式並不要指定 encoding。)可用的模式有:

字符

含義

'r'

讀取(默認)

'w'

寫入,並先截斷文件

'x'

排它性創建,如果文件已存在則失敗

'a'

寫入,如果文件存在則在末尾追加

'b'

二進制模式

't'

文本模式(默認)

'+'

更新磁盤文件(讀取並寫入)

默認的模式是 'r' (打開並讀取文本,同 'rt' )。對於二進制寫入, 'w+b' 模式打開並把文件截斷成 0 字節; 'r+b' 則不會截斷。

正如在 概述 中提到的,Python區分二進制和文本I/O。以二進制模式打開的文件(包括 mode 參數中的 'b' )返回的內容爲 bytes`對象,不進行任何解碼。在文本模式下(默認情況下,或者在 *mode* 參數中包含 `'t'` )時,文件內容返回爲 str ,首先使用指定的 encoding (如果給定)或者使用平臺默認的的字節編碼解碼。

此外還允許使用一個模式字符 'U',該字符已不再具有任何效果,並被視爲已棄用。 之前它會在文本模式中啓用 universal newlines,這在 Python 3.0 中成爲默認行爲。 請參閱 newline 形參的文檔瞭解更多細節。

註解

Python不依賴於底層操作系統的文本文件概念;所有處理都由Python本身完成,因此與平臺無關。

buffering 是一個可選的整數,用於設置緩衝策略。傳遞0以切換緩衝關閉(僅允許在二進制模式下),1選擇行緩衝(僅在文本模式下可用),並且>1的整數以指示固定大小的塊緩衝區的大小(以字節爲單位)。如果沒有給出 buffering 參數,則默認緩衝策略的工作方式如下:

  • 二進制文件以固定大小的塊進行緩衝;使用啓發式方法選擇緩衝區的大小,嘗試確定底層設備的“塊大小”或使用 io.DEFAULT_BUFFER_SIZE。在許多系統上,緩衝區的長度通常爲4096或8192字節。

  • “交互式”文本文件( isatty() 返回 True 的文件)使用行緩衝。其他文本文件使用上述策略用於二進制文件。

encoding 是用於解碼或編碼文件的編碼的名稱。這應該只在文本模式下使用。默認編碼是依賴於平臺的(不 管 locale.getpreferredencoding() 返回何值),但可以使用任何Python支持的 text encoding 。有關支持的編碼列表,請參閱 codecs 模塊。

errors 是一個可選的字符串參數,用於指定如何處理編碼和解碼錯誤 - 這不能在二進制模式下使用。可以使用各種標準錯誤處理程序(列在 錯誤處理方案 ),但是使用 codecs.register_error() 註冊的任何錯誤處理名稱也是有效的。標準名稱包括:

  • 如果存在編碼錯誤,'strict' 會引發 ValueError 異常。 默認值 None 具有相同的效果。

  • 'ignore' 忽略錯誤。請注意,忽略編碼錯誤可能會導致數據丟失。

  • 'replace' 會將替換標記(例如 '?' )插入有錯誤數據的地方。

  • 'surrogateescape' 將表示任何不正確的字節作爲Unicode專用區中的代碼點,範圍從U+DC80到U+DCFF。當在寫入數據時使用 surrogateescape 錯誤處理程序時,這些私有代碼點將被轉回到相同的字節中。這對於處理未知編碼的文件很有用。

  • 只有在寫入文件時才支持 'xmlcharrefreplace'。編碼不支持的字符將替換爲相應的XML字符引用 &#nnn;

  • 'backslashreplace' 用Python的反向轉義序列替換格式錯誤的數據。

  • 'namereplace' (也只在編寫時支持)用 \N{...} 轉義序列替換不支持的字符。

newline 控制 universal newlines 模式如何生效(它僅適用於文本模式)。它可以是 None'''\n''\r' 和 '\r\n'。它的工作原理:

  • 從流中讀取輸入時,如果 newline 爲 None,則啓用通用換行模式。輸入中的行可以以 '\n''\r' 或 '\r\n' 結尾,這些行被翻譯成 '\n' 在返回呼叫者之前。如果它是 '',則啓用通用換行模式,但行結尾將返回給調用者未翻譯。如果它具有任何其他合法值,則輸入行僅由給定字符串終止,並且行結尾將返回給未調用的調用者。

  • 將輸出寫入流時,如果 newline 爲 None,則寫入的任何 '\n' 字符都將轉換爲系統默認行分隔符 os.linesep。如果 newline 是 '' 或 '\n',則不進行翻譯。如果 newline 是任何其他合法值,則寫入的任何 '\n' 字符將被轉換爲給定的字符串。

如果 closefd 是 False 並且給出了文件描述符而不是文件名,那麼當文件關閉時,底層文件描述符將保持打開狀態。如果給出文件名則 closefd 必須爲 True (默認值),否則將引發錯誤。

可以通過傳遞可調用的 opener 來使用自定義開啓器。然後通過使用參數( fileflags )調用 opener 獲得文件對象的基礎文件描述符。 opener 必須返回一個打開的文件描述符(使用 os.open as opener 時與傳遞 None 的效果相同)。

新創建的文件是 不可繼承的

下面的示例使用 os.open() 函數的 dir_fd 的形參,從給定的目錄中用相對路徑打開文件:

>>>

>>> import os
>>> dir_fd = os.open('somedir', os.O_RDONLY)
>>> def opener(path, flags):
...     return os.open(path, flags, dir_fd=dir_fd)
...
>>> with open('spamspam.txt', 'w', opener=opener) as f:
...     print('This will be written to somedir/spamspam.txt', file=f)
...
>>> os.close(dir_fd)  # don't leak a file descriptor

open() 函數所返回的 file object 類型取決於所用模式。 當使用 open() 以文本模式 ('w''r''wt''rt' 等) 打開文件時,它將返回 io.TextIOBase (特別是 io.TextIOWrapper) 的一個子類。 當使用緩衝以二進制模式打開文件時,返回的類是 io.BufferedIOBase 的一個子類。 具體的類會有多種:在只讀的二進制模式下,它將返回 io.BufferedReader;在寫入二進制和追加二進制模式下,它將返回 io.BufferedWriter,而在讀/寫模式下,它將返回 io.BufferedRandom。 當禁用緩衝時,則會返回原始流,即 io.RawIOBase 的一個子類 io.FileIO

另請參閱文件操作模塊,例如 fileinputio (聲明瞭 open())、osos.pathtempfile 和 shutil

在 3.3 版更改:
  • 增加了 opener 形參。

  • 增加了 'x' 模式。

  • 過去觸發的 IOError,現在是 OSError 的別名。

  • 如果文件已存在但使用了排它性創建模式( 'x' ),現在會觸發 FileExistsError

在 3.4 版更改:
  • 文件現在禁止繼承。

Deprecated since version 3.4, will be removed in version 3.9: 'U' 模式。

在 3.5 版更改:
  • 如果系統調用被中斷,但信號處理程序沒有觸發異常,此函數現在會重試系統調用,而不是觸發 InterruptedError 異常 (原因詳見 PEP 475)。

  • 增加了 'namereplace' 錯誤處理接口。

在 3.6 版更改:
  • 增加對實現了 os.PathLike 對象的支持。

  • 在 Windows 上,打開一個控制檯緩衝區將返回 io.RawIOBase 的子類,而不是 io.FileIO


看完官方的open函數定義可能有點懵,下面就詳細的講解下open函數的定義和用法。

1.open函數基礎內容

1.1 定義

open函數其實就是對文件的操作,可以讀取文件打開文件修改文件保存文件,等等。

當然open函數還可以用在複製圖片(爬蟲等)多個場景,後續在集體場景中再詳細說明。

舉例,打開同目錄下demo.txt文件:

'''open'''
open('demo.txt')

 

1.2 open函數的參數組成

直接通過ctrl+鼠標左鍵點進open函數查看:

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 OSError 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, '', '\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 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.
    """
    pass

單獨拉出參數部分

def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): 

可以看到之前舉例中open('demo.txt'),'demo.txt'表示的是file,而其他參數mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True都是默認參數,所以直接運行open('demo.txt')也不會報錯。

 

1.3 open函數參數的作用

既然上面提到那麼多參數,那麼這些參數到底是幹嘛的?

  • file就是表示文件名,也可以表示路徑。當然目前沒有涉及到os模塊的學習,所以所有的操作都基於同目錄下。
  • mode表示模式,後面會詳細去講解mode各個參數的用法。
  • buffering:如果 buffering 的值被設爲 0,就不會有寄存。如果 buffering 的值取 1,訪問文件時會寄存行。如果將 buffering 的值設爲大於 1 的整數,表明了這就是的寄存區的緩衝大小。如果取負值,寄存區的緩衝大小則爲系統默認。通常情況下、建議大家在使用 open() 函數時打開緩衝區,即不需要修改 buffing 參數的值。

    如果 buffing 參數的值爲 0(或者 False),則表示在打開指定文件時不使用緩衝區;如果 buffing 參數值爲大於 1 的整數,該整數用於指定緩衝區的大小(單位是字節);如果 buffing 參數的值爲負數,則代表使用默認的緩衝區大小。

    爲什麼呢?原因很簡單,目前爲止計算機內存的 I/O 速度仍遠遠高於計算機外設(例如鍵盤、鼠標、硬盤等)的 I/O 速度,如果不使用緩衝區,則程序在執行 I/O 操作時,內存和外設就必須進行同步讀寫操作,也就是說,內存必須等待外設輸入(輸出)一個字節之後,才能再次輸出(輸入)一個字節。這意味着,內存中的程序大部分時間都處於等待狀態。

    而如果使用緩衝區,則程序在執行輸出操作時,會先將所有數據都輸出到緩衝區中,然後繼續執行其它操作,緩衝區中的數據會有外設自行讀取處理;同樣,當程序執行輸入操作時,會先等外設將數據讀入緩衝區中,無需同外設做同步讀寫操作。
  • encoding:編碼格式,常見的編碼格式有ASCIIANSIGBKGB2312UTF-8GB18030UNICODE等。一般我們用utf-8作爲encoding的編碼格式。
  • errors:errors是一個可選字符串,用於指定編碼錯誤的方式,通過“strict”用於在編碼錯誤時拋出ValueError異常(默認的None具有相同的效果),或者通過“ignore”來忽略錯誤。(注意忽略編碼錯誤會導致數據丟失。)
  • newline:換行符的處理。
  • closefd:如果closefd爲False,底層文件描述符將保持打開狀態。當文件關閉時。當給定文件名時,這不起作用。在這種情況下一定是真的。

而通常對於open函數來說,我們常用到的有file、mode、encoding這三個參數,其他的一般用不到,就用默認參數即可。

 

1.4 mode模式所有參數用法

'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)
模式 描述
r 以只讀方式打開文件。文件的指針將會放在文件的開頭。這是默認模式。
rb 以二進制格式打開一個文件用於只讀。文件指針將會放在文件的開頭。這是默認模式。
r+ 打開一個文件用於讀寫。文件指針將會放在文件的開頭。
rb+ 以二進制格式打開一個文件用於讀寫。文件指針將會放在文件的開頭。
w 打開一個文件只用於寫入。如果該文件已存在則打開文件,並從開頭開始編輯,即原有內容會被刪除。如果該文件不存在,創建新文件。
wb 以二進制格式打開一個文件只用於寫入。如果該文件已存在則打開文件,並從開頭開始編輯,即原有內容會被刪除。如果該文件不存在,創建新文件。
w+ 打開一個文件用於讀寫。如果該文件已存在則打開文件,並從開頭開始編輯,即原有內容會被刪除。如果該文件不存在,創建新文件。
wb+ 以二進制格式打開一個文件用於讀寫。如果該文件已存在則打開文件,並從開頭開始編輯,即原有內容會被刪除。如果該文件不存在,創建新文件。
a 打開一個文件用於追加。如果該文件已存在,文件指針將會放在文件的結尾。也就是說,新的內容將會被寫入到已有內容之後。如果該文件不存在,創建新文件進行寫入。
ab 以二進制格式打開一個文件用於追加。如果該文件已存在,文件指針將會放在文件的結尾。也就是說,新的內容將會被寫入到已有內容之後。如果該文件不存在,創建新文件進行寫入。
a+ 打開一個文件用於讀寫。如果該文件已存在,文件指針將會放在文件的結尾。文件打開時會是追加模式。如果該文件不存在,創建新文件用於讀寫。
ab+ 以二進制格式打開一個文件用於追加。如果該文件已存在,文件指針將會放在文件的結尾。如果該文件不存在,創建新文件用於讀寫。

所有的用法其實可以分爲三部分:

  • r 讀模式
  • w 寫模式
  • a 追加模式

r模式就是讀(read),可以通過表格看到r、rb、r+、rb+的意義和用法。

w模式就是寫(write),也就是對文件的操作,同樣可以通過w、wb、w+、wb+對文件進行寫入操作,但需要注意的是,w模式會覆蓋之前文件的內容:如果該文件已存在則打開文件,並從開頭開始編輯,即原有內容會被刪除。如果該文件不存在,創建新文件。所以一般不輕易使用w模式,有點危險。

a模式就是追加寫入模式,和w模式相比a模式更加人性化,不會覆蓋之前的內容,同時也保證新內容的記錄。

x是原創模式,下面會詳細進行說明。

b模式表示2進制模式,比如圖片,圖片就是二進制數據。

 

1.5 x原創模式

幾乎所有的python學習資料裏對open函數的講解都沒有涉及到x原創模式這個概念,這裏簡單的講解下:

由於w模式會直接覆蓋之前的文件,所以引入了x原創模式的概念,也就是如果之前有同名文件,會直接報錯!

所以用x模式很保險,會防止同名文件覆蓋的情況,導致文件信息丟失而造成不可挽回的影響,對原創的內容具有保護功能。

 

1.6 對於文件讀取的深入理解

其實所有的讀取都是基於文件指針的位置,通過指針的移動從而讀取所有文件內容。

就像我們打開文件去讀取是一樣的,打開一個文件後,指針通常會在第一行第一列(第一個字符),對於默認的mode = r模式來說就是表示這個意思:

r 以只讀方式打開文件。文件的指針將會放在文件的開頭。這是默認模式。

所以只要r開頭的模式都是表示文件指針放在文件的開頭位置。

r 以只讀方式打開文件。文件的指針將會放在文件的開頭。這是默認模式。
rb 以二進制格式打開一個文件用於只讀。文件指針將會放在文件的開頭。這是默認模式。
r+ 打開一個文件用於讀寫。文件指針將會放在文件的開頭。
rb+ 以二進制格式打開一個文件用於讀寫。文件指針將會放在文件的開頭。

而w模式同樣也是表示文件指針放在文件開頭的位置。

w 打開一個文件只用於寫入。如果該文件已存在則打開文件,並從開頭開始編輯,即原有內容會被刪除。如果該文件不存在,創建新文件。
wb 以二進制格式打開一個文件只用於寫入。如果該文件已存在則打開文件,並從開頭開始編輯,即原有內容會被刪除。如果該文件不存在,創建新文件。
w+ 打開一個文件用於讀寫。如果該文件已存在則打開文件,並從開頭開始編輯,即原有內容會被刪除。如果該文件不存在,創建新文件。
wb+ 以二進制格式打開一個文件用於讀寫。如果該文件已存在則打開文件,並從開頭開始編輯,即原有內容會被刪除。如果該文件不存在,創建新文件。

r模式和w模式也是我們最爲常用,也是最普遍的mode模式用法。一個用來讀,一個用來寫。

那麼哪些是指針從結尾開始?a模式開頭的都是表示文件指針放在文件的結尾。

a 打開一個文件用於追加。如果該文件已存在,文件指針將會放在文件的結尾。也就是說,新的內容將會被寫入到已有內容之後。如果該文件不存在,創建新文件進行寫入。
ab 以二進制格式打開一個文件用於追加。如果該文件已存在,文件指針將會放在文件的結尾。也就是說,新的內容將會被寫入到已有內容之後。如果該文件不存在,創建新文件進行寫入。
a+ 打開一個文件用於讀寫。如果該文件已存在,文件指針將會放在文件的結尾。文件打開時會是追加模式。如果該文件不存在,創建新文件用於讀寫。
ab+ 以二進制格式打開一個文件用於追加。如果該文件已存在,文件指針將會放在文件的結尾。如果該文件不存在,創建新文件用於讀寫。

 

1.7 文件操作的流程

文件操作的流程不復雜,跟平時怎麼讀取、操作文件是一樣的:

  • 保證在同一文件夾
  • 創建文件
  • 打開文件

用open函數打開並讀取文件,用一個變量比如 file 接收。

  • 讀取文件

file.read()

file.readline()

兩者區別會放在文章的最後。

  • 打印文件內容

可以通過print語句打印文件內容。

  • 寫入文件

file.write(),write括號內要加寫入的內容。

  • 打印文件內容

可以通過print語句打印文件內容。

  • 關閉文件

file.close()

需要注意的是,每次打開文件進行操作後,一定要去關閉文件,在進行下次操作。

如果不關閉,下次再打開該文件進行操作時會出現異常,跟資源調度有關,這個需要注意!

 


2.open函數的實戰應用

講了那麼多紙上談兵,現在開始正兒八經的進行應用,目前默認爲所有需要操作的文件都在同一文件夾進行:

2.1 普通操作

  • 創建文件

  • 讀取操作:打開文件,讀取當前內容。
file = open('demo.txt',mode='r',encoding='utf-8')
data = file.read()
print(data)

很明顯,由於沒有給文件寫入內容,這裏什麼也讀不到。

  • 寫入操作:對demo文件寫入hello world,並讀取。
file = open('demo.txt',mode='w',encoding='utf-8')
data = file.write('hello world')
file.close()
file = open('demo.txt',mode='r',encoding='utf-8')
print(file.read())
file.close()
hello world

 

2.2上下文表達式

由於每次打開文件後都要關閉,怕忘記寫close,這裏引入with語句來替代傳統的open函數用法。用with語句就不用每次手動關閉文件了。

with語法:

with open(file) as 變量:
    代碼語句

舉例:

with open('demo.txt',mode='r',encoding='utf-8') as f:
    print(f.read())
hello world!

w模式:

with open('demo.txt',mode='w',encoding='utf-8') as f:
    f.write('Happy everyday!')

with open('demo.txt',mode='r',encoding='utf-8') as f:
    print(f.read())
Happy everyday!

a模式:

with open('demo.txt',mode='a',encoding='utf-8') as f:
    f.write('Happy everyday!')

with open('demo.txt',mode='r',encoding='utf-8') as f:
    print(f.read())
Happy everyday!Happy everyday!

 

2.3 read()和readline()區別

read()返回值得到是一個字符串,而readline()得到的是一個列表:

with open('demo.txt',mode='r',encoding='utf-8') as f:
    print(f.read())
    print(type(f.read()))
Happy everyday!
Happy everyday!
Happy everyday!
Happy everyday!
Happy everyday!
Happy everyday!
<class 'str'>
with open('demo.txt',mode='r',encoding='utf-8') as f:
    print(f.readlines())
    print(type(f.readlines()))
['Happy everyday!\n', 'Happy everyday!\n', 'Happy everyday!\n', 'Happy everyday!\n', 'Happy everyday!\n', 'Happy everyday!']
<class 'list'>

readline()會去讀取每一行,將每一行的內容作爲一個列表的元素,存放在列表中。

而read()是將所有的內容放在一個字符串中並返回。這是兩者最大的區別。

至於什麼時候用read()什麼時候用readline()看具體需求。

 

目前涉及到的open函數用法是基於同目錄進行,在後期學習中學到os路徑模塊時再利用open函數去操作其他目錄下的文件。


以上是《Python學習16:open內置函數講解》的所有內容,open函數的相關練習會在出現在之後習題訓練中,敬請期待。原創不易,如果喜歡請點贊和關注,謝謝大家的支持!

想獲得免費的學習資料請添加微信公衆號——,非常感謝大家的關注和支持!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章