python怎麼驗證檔案是否存在
os模組
os模組中的os.path.exists(path)可以檢測檔案或資料夾是否存在,path為檔案/資料夾的名字/絕對路徑。返回結果為True/False
print os.path.exists("/untitled/chapter3.py")print os.path.exists("chapter3.py")
這種用法既能檢測檔案也能檢測資料夾,這也帶來問題,假如我想找一個命名為helloworld的檔案,使用exists可能命中同名的helloworld資料夾。這時使用os.path.isdir()和os.path.isfile()可以加以區分。如果進一步想判斷是否可以操作檔案,可以使用os.access(path, model),model為操作模式,具體如下
if __name__ == '__main__': if os.access("/untitled/chapter3.py", os.F_OK): print "File path is exist." if os.access("/untitled/chapter3.py", os.R_OK): print "File is accessible to read" if os.access("/untitled/chapter3.py", os.W_OK): print "File is accessible to write" if os.access("/untitled/chapter3.py", os.X_OK): print "File is accessible to execute"
try語句
對檔案最簡單的操作方法是直接使用open()方法,但是檔案不存在,或發生許可權問題時open方法會報錯,所以配合try語句使用來捕捉一異常。try...open語法簡單優雅,可讀性強,而且不需要引入任何模組
if __name__ == '__main__': try: f = open("/untitled/chapter3.py") f.close() except IOError: print "File is not accessible."
pathlib模組
在python2中pathlib屬於第三方模組,需要單獨安裝。但是python3中pathlib已經是內建模組了
pathlib用法簡單,與open類似。首先使用pathlib建立物件,進而使用exists(),is_file()等方法
if __name__ == '__main__': path = pathlib.Path("chapter3.py") print path.exists() print path.is_file()
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/4830/viewspace-2835692/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- jquery怎麼樣判斷檔案是否存在jQuery
- 驗證資料是否存在
- python 判斷檔案是否存在Python
- python判斷檔案是否存在等操作Python
- golang判斷檔案是否存在Golang
- vc判斷檔案是否存在
- Python 判斷檔案是否存在的三種方法Python
- Python檢驗一個檔案是否存在,如果不在就自己填寫內容。Python
- java判斷檔案是否存在並建立檔案Java
- Python3中如何檢查檔案是否存在?Python教程!Python
- Python3檢查檔案是否存在的常用方法!Python
- 怎麼判斷mysql表是否存在MySql
- 校驗區間是否存在重疊(Python)Python
- Python3如何檢查檔案或資料夾是否存在?Python
- Python判斷一個檔案中的字串是否存在於另外一個檔案中Python字串
- js如何判斷指定的檔案是否存在JS
- C# 判斷遠端檔案是否存在C#
- shell 判斷檔案或路徑是否存在
- 使用ajax方式驗證使用者名稱是否存在程式碼
- 判斷檔案中是否存在中文字元字元
- Python使用os模組、Try語句、pathlib模組判斷檔案是否存在Python
- python怎麼建立文字檔案Python
- windows無法驗證此檔案的數字簽名什麼原因怎麼解決Windows
- python怎麼讀取配置檔案Python
- VBA判斷指定的資料夾或檔案是否存在
- ajax實現的驗證使用者名稱是否存在程式碼例項
- python怎麼寫txt檔案路徑Python
- oracle資料檔案驗證工具Oracle
- Linux - 判斷檔案/目錄是否存在/具有許可權Linux
- python中快速驗證輸入的是否為迴文Python
- 資料檔案拷貝檔案頭驗證錯誤
- 怎麼看python是否安裝成功Python
- C語言判斷檔案是否存在,判斷檔案可讀可寫可執行C語言
- Oracle基礎結構之OS驗證和口令檔案驗證Oracle
- python列表中是否存在某個元素Python
- python檔案無法讀寫怎麼辦Python
- python3檔案開頭怎麼寫Python
- Python中open函式怎麼操作檔案Python函式