這裡主要想說的是File()和Open()這兩個函數的主要用途,因為自己在用的時候就迷糊,到底這倆個有什麼區別
一般我們都知道操作檔案的基本根式是
with open("filePath","r") as fobj
for line in fobj
.......
檔案的操作和很多程式設計語言一樣,一定要記得Close開啟的檔案對象。其中檔案的開啟檔案也有r(讀)w(截斷寫)a(追加方式),常用的就這幾種,還有些特殊的就查協助文檔吧。這些都好理解,最讓我迷惑的是File()和Open()這兩個有什麼用,如果是一樣的,幹嘛不統一呢。先看英文吧
>不多介紹先看看英文資料
兩種都是build-in function
file( filename[, mode[, bufsize]])
Constructor function for the file type, described further in section 3.9, ``File Objects''. The constructor's arguments are the same as those of the open() built-in function described below.
When opening a file, it's preferable to use open() instead of invoking this constructor directly. file is more suited to type testing (for example, writing "isinstance(f, file)").
open( filename[, mode[, bufsize]])
Open a file, returning an object of the file type described in section 3.9, ``File Objects''. If the file cannot be opened, IOError is raised. When opening a file, it's preferable to use open() instead of invoking the file constructor directly.....
可以這麼來解釋
file是file類型的建構函式,雖然也可以開啟檔案,但更提倡使用open的方式來使用。理論上兩者應該沒有本質的區別