2010-08-02 73 views
17
def CreateDirectory(pathName): 
    if not os.access(pathName, os.F_OK): 
     os.makedirs(pathName) 

與:Python - os.access和os.path.exists之間的區別?

def CreateDirectory(pathName): 
    if not os.path.exists(pathName): 
     os.makedirs(pathName) 

我明白os.access是一個更靈活一點,因爲你可以檢查RWE屬性以及路徑的存在,但有一些細微的差別,我在這裏失蹤之間這兩個實現?

+3

如果文檔是可信的,它比答案所說的更加微妙。 'os.F_OK'模式專門用於測試是否存在,而不是權限;而對於'os.path.exists()':「在某些平臺上,如果在所請求的文件上沒有授予權限來執行os.stat(),則該函數可能返回False,即使路徑物理上存在。 [FreeBSD手冊頁](http://www.freebsd.org/cgi/man.cgi?query=access&sektion=2)表示'access'比'stat'更便宜。 – 2012-10-08 19:15:03

回答

13

更好地捕捉異常而不是試圖阻止它。有跡象表明,makedirs可以失敗

def CreateDirectory(pathName): 
    try: 
     os.makedirs(pathName) 
    except OSError, e: 
     # could be that the directory already exists 
     # could be permission error 
     # could be file system is full 
     # look at e.errno to determine what went wrong 

要回答你的問題,os.access可以測試權限讀取或寫入文件(如登錄的用戶)是數不勝數的原因。 os.path.exists只是告訴你是否有東西存在或不存在。我希望大多數人會使用os.path.exists來測試文件的存在,因爲它更容易記住。

4

os.access測試路徑是否可以被當前用戶訪問 os.path.exists檢查路徑是否存在。即使路徑存在,os.access也可能返回False