新聞中心
os模塊

創(chuàng)新互聯(lián)為您提適合企業(yè)的網(wǎng)站設(shè)計?讓您的網(wǎng)站在搜索引擎具有高度排名,讓您的網(wǎng)站具備超強的網(wǎng)絡(luò)競爭力!結(jié)合企業(yè)自身,進行網(wǎng)站設(shè)計及把握,最后結(jié)合企業(yè)文化和具體宗旨等,才能創(chuàng)作出一份性化解決方案。從網(wǎng)站策劃到成都網(wǎng)站設(shè)計、成都網(wǎng)站制作, 我們的網(wǎng)頁設(shè)計師為您提供的解決方案。
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ū)分。如果進一步想判斷是否可以操作文件,可以使用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語句(更多教程,請點擊python學習網(wǎng))
對文件最簡單的操作方法是直接使用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)建對象,進而使用exists(),is_file()等方法
if __name__ == '__main__':
path = pathlib.Path("chapter3.py")
print path.exists()
print path.is_file() 新聞標題:創(chuàng)新互聯(lián)Python教程:python如何確定文件是否存在
標題來源:http://m.fisionsoft.com.cn/article/cdohjii.html


咨詢
建站咨詢
