99热99这里只有精品6国产,亚洲中文字幕在线天天更新,在线观看亚洲精品国产福利片 ,久久久久综合网

歡迎加入QQ討論群258996829
麥子學院 頭像
蘋果6袋
6
麥子學院

python判斷文件是否存在

發(fā)布時間:2018-03-20 23:12  回復:0  查看:2754   最后回復:2018-03-20 23:12  

在python開發(fā)中,我們常常會遇到判斷文件是否存在的需求,今天和大家分享的就是這部分內(nèi)容,希望對大家學習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()可以加以區(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語句

  對文件最簡單的操作方法是直接使用open()方法,但是文件不存在,或發(fā)生權限問題時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模塊

  在python2pathlib屬于第三方模塊,需要單獨安裝。但是python3pathlib已經(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()

 

 

來源:推酷

您還未登錄,請先登錄

熱門帖子

最新帖子

?