python 判斷文件是否存在


在業務中遇到了需要判斷文件是否存在的需求,所以順便整理一下python判斷文件是否存在的方法。在操作文件前,檢查文件是否存在也是一個良好的編程習慣。通常來說,有三種常見方式來判斷文件夾或文件是否存在,分別是os模塊,try語句和pathlib模塊。

 

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()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM