內置函數open()
是處理文件的好方法。此方法將檢查文件是否存在于指定的路徑中,如果存在,它將返回文件對象,否則它將返回錯誤。
**open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)** #where file specifies the path
打開()參數:
本例中需要 8 個參數,其余都是可選的。在這種模式下類型有很多選項(r:讀,w:寫,x:獨占創建,a:追加,t:文本模式,b:二進制模式,+:更新(讀,寫))
參數 | 描述 | 必需/可選 |
---|---|---|
文件 | 類路徑對象 | 需要 |
方式 | 模式(可選)-打開文件時的模式。如果未提供,則默認為“r” | 可選擇的 |
減輕 | 用于設置緩沖策略 | 可選擇的 |
編碼 | 編碼格式 | 可選擇的 |
錯誤 | 指定如何處理編碼/解碼錯誤的字符串 | 可選擇的 |
新行 | 換行符模式如何工作(可用值:無' ',' \n ',' r '和' \r\n ') | 可選擇的 |
關門了 | 必須為真(默認);如果給定為其他值,將引發異常 | 可選擇的 |
開啟工具 | 定制的開瓶器;必須返回打開的文件描述符 | 可選擇的 |
打開()返回值
如果文件存在于指定的路徑中,它將返回一個文件對象,該對象可用于讀取、寫入和修改。如果文件不存在,它將引發 FileNotFoundError 異常。
| 投入 | 返回值 | | 如果文件存在 | 文件對象 |
Python 中open()
方法的示例
示例 1:如何用 Python 打開文件?
# opens test.text file of the current directory
f = open("test.txt")
# specifying the full path
f = open("C:/Python33/README.txt")
輸出:
Since the mode is omitted, the file is opened in 'r' mode; opens for reading.
示例 2:提供打開模式()
# opens the file in reading mode
f = open("path_to_file", mode='r')
# opens the file in writing mode
f = open("path_to_file", mode = 'w')
# opens for writing to the end
f = open("path_to_file", mode = 'a')
輸出:
Open a file in read,write and append mode.