新聞中心
os模塊

os模塊中的os.path.exists(path)可以檢測文件或文件夾是否存在,path為文件/文件夾的名字/絕對路徑。返回結(jié)果為True/False
print os.path.exists("/untitled/chapter3.py")print os.path.exists("chapter3.py")這種用法既能檢測文件也能檢測文件夾,這也帶來問題,假如我想找一個命名為helloworld的文件,使用exists可能命中同名的helloworld文件夾。這時使用os.path.isdir()和os.path.isfile()可以加以區(qū)分。如果進(jìn)一步想判斷是否可以操作文件,可以使用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"python學(xué)習(xí)網(wǎng),免費的python學(xué)習(xí)網(wǎng)站,歡迎在線學(xué)習(xí)!
try語句
對文件最簡單的操作方法是直接使用open()方法,但是文件不存在,或發(fā)生權(quán)限問題時open方法會報錯,所以配合try語句使用來捕捉一異常。try...open語法簡單優(yōu)雅,可讀性強,而且不需要引入任何模塊
if __name__ == '__main__':
try:
f = open("/untitled/chapter3.py")
f.close()
except IOError:
print "File is not accessible."pathlib模塊
在python2中pathlib屬于第三方模塊,需要單獨安裝。但是python3中pathlib已經(jīng)是內(nèi)建模塊了
pathlib用法簡單,與open類似。首先使用pathlib創(chuàng)建對象,進(jìn)而使用exists(),is_file()等方法
if __name__ == '__main__':
path = pathlib.Path("chapter3.py")
print path.exists()
print path.is_file() 當(dāng)前標(biāo)題:創(chuàng)新互聯(lián)Python教程:python怎么驗證文件是否存在
分享網(wǎng)址:http://fisionsoft.com.cn/article/dhcdsjp.html


咨詢
建站咨詢
