掃二維碼與項(xiàng)目經(jīng)理溝通
我們?cè)谖⑿派?4小時(shí)期待你的聲音
解答本文疑問(wèn)/技術(shù)咨詢/運(yùn)營(yíng)咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流
內(nèi)置函數(shù)open()是處理文件的好方法。此方法將檢查文件是否存在于指定的路徑中,如果存在,它將返回文件對(duì)象,否則它將返回錯(cuò)誤。

創(chuàng)新互聯(lián)從2013年開(kāi)始,先為佛山等服務(wù)建站,佛山等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為佛山企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問(wèn)題。
**open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)** #where file specifies the path
本例中需要 8 個(gè)參數(shù),其余都是可選的。在這種模式下類(lèi)型有很多選項(xiàng)(r:讀,w:寫(xiě),x:獨(dú)占創(chuàng)建,a:追加,t:文本模式,b:二進(jìn)制模式,+:更新(讀,寫(xiě)))
| 參數(shù) | 描述 | 必需/可選 |
|---|---|---|
| 文件 | 類(lèi)路徑對(duì)象 | 需要 |
| 方式 | 模式(可選)-打開(kāi)文件時(shí)的模式。如果未提供,則默認(rèn)為“r” | 可選擇的 |
| 減輕 | 用于設(shè)置緩沖策略 | 可選擇的 |
| 編碼 | 編碼格式 | 可選擇的 |
| 錯(cuò)誤 | 指定如何處理編碼/解碼錯(cuò)誤的字符串 | 可選擇的 |
| 新行 | 換行符模式如何工作(可用值:無(wú)' ',' \n ',' r '和' \r\n ') | 可選擇的 |
| 關(guān)門(mén)了 | 必須為真(默認(rèn));如果給定為其他值,將引發(fā)異常 | 可選擇的 |
| 開(kāi)啟工具 | 定制的開(kāi)瓶器;必須返回打開(kāi)的文件描述符 | 可選擇的 |
如果文件存在于指定的路徑中,它將返回一個(gè)文件對(duì)象,該對(duì)象可用于讀取、寫(xiě)入和修改。如果文件不存在,它將引發(fā) FileNotFoundError 異常。
| 投入 | 返回值 | | 如果文件存在 | 文件對(duì)象 |
open()方法的示例 # 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.
# 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. 
我們?cè)谖⑿派?4小時(shí)期待你的聲音
解答本文疑問(wèn)/技術(shù)咨詢/運(yùn)營(yíng)咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流