新聞中心
os模塊中的os.path.exists(path)可以檢測文件或文件夾是否存在,path為文件/文件夾的名字/絕對(duì)路徑。返回結(jié)果為True/False

專注于為中小企業(yè)提供成都網(wǎng)站制作、做網(wǎng)站服務(wù),電腦端+手機(jī)端+微信端的三站合一,更高效的管理,為中小企業(yè)三江侗免費(fèi)做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動(dòng)了上千家企業(yè)的穩(wěn)健成長,幫助中小企業(yè)通過網(wǎng)站建設(shè)實(shí)現(xiàn)規(guī)模擴(kuò)充和轉(zhuǎn)變。
print os.path.exists("/untitled/chapter3.py")print os.path.exists("chapter3.py")這種用法既能檢測文件也能檢測文件夾,這也帶來問題,假如我想找一個(gè)命名為helloworld的文件,使用exists可能命中同名的helloworld文件夾。這時(shí)使用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),免費(fèi)的python學(xué)習(xí)網(wǎng)站,歡迎在線學(xué)習(xí)!
try語句
對(duì)文件最簡單的操作方法是直接使用open()方法,但是文件不存在,或發(fā)生權(quán)限問題時(shí)open方法會(huì)報(bào)錯(cuò),所以配合try語句使用來捕捉一異常。try...open語法簡單優(yōu)雅,可讀性強(qiáng),而且不需要引入任何模塊
if __name__ == '__main__':
try:
f = open("/untitled/chapter3.py")
f.close()
except IOError:
print "File is not accessible."pathlib模塊
在python2中pathlib屬于第三方模塊,需要單獨(dú)安裝。但是python3中pathlib已經(jīng)是內(nèi)建模塊了
pathlib用法簡單,與open類似。首先使用pathlib創(chuàng)建對(duì)象,進(jìn)而使用exists(),is_file()等方法
if __name__ == '__main__':
path = pathlib.Path("chapter3.py")
print path.exists()
print path.is_file() 本文名稱:創(chuàng)新互聯(lián)Python教程:python怎么檢查文件是否存在
轉(zhuǎn)載來源:http://www.dlmjj.cn/article/djjseoh.html


咨詢
建站咨詢
