Python 如何測(cè)試文件是否存在
問題
你想測(cè)試一個(gè)文件或目錄是否存在。
解決方案
使用 os.path 模塊來測(cè)試一個(gè)文件或目錄是否存在。比如:
>>> import os>>> os.path.exists(’/etc/passwd’)True>>> os.path.exists(’/tmp/spam’)False>>>
你還能進(jìn)一步測(cè)試這個(gè)文件時(shí)什么類型的。 在下面這些測(cè)試中,如果測(cè)試的文件不存在的時(shí)候,結(jié)果都會(huì)返回False:
>>> # Is a regular file>>> os.path.isfile(’/etc/passwd’)True>>> # Is a directory>>> os.path.isdir(’/etc/passwd’)False>>> # Is a symbolic link>>> os.path.islink(’/usr/local/bin/python3’)True>>> # Get the file linked to>>> os.path.realpath(’/usr/local/bin/python3’)’/usr/local/bin/python3.3’>>>
如果你還想獲取元數(shù)據(jù)(比如文件大小或者是修改日期),也可以使用 os.path 模塊來解決:
>>> os.path.getsize(’/etc/passwd’)3669>>> os.path.getmtime(’/etc/passwd’)1272478234.0>>> import time>>> time.ctime(os.path.getmtime(’/etc/passwd’))’Wed Apr 28 13:10:34 2010’>>>
討論
使用 os.path 來進(jìn)行文件測(cè)試是很簡單的。 在寫這些腳本時(shí),可能唯一需要注意的就是你需要考慮文件權(quán)限的問題,特別是在獲取元數(shù)據(jù)時(shí)候。比如:
>>> os.path.getsize(’/Users/guido/Desktop/foo.txt’)Traceback (most recent call last): File '<stdin>', line 1, in <module> File '/usr/local/lib/python3.3/genericpath.py', line 49, in getsize return os.stat(filename).st_sizePermissionError: [Errno 13] Permission denied: ’/Users/guido/Desktop/foo.txt’>>>
以上就是Python 如何測(cè)試文件是否存在的詳細(xì)內(nèi)容,更多關(guān)于Python 測(cè)試文件的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. PHP VS ASP2. python裝飾器三種裝飾模式的簡單分析3. 詳解JS ES6編碼規(guī)范4. 詳解Python模塊化編程與裝飾器5. JavaScript中的AOP編程的基本實(shí)現(xiàn)6. JavaScript Reduce使用詳解7. Spring security 自定義過濾器實(shí)現(xiàn)Json參數(shù)傳遞并兼容表單參數(shù)(實(shí)例代碼)8. python使用ctypes庫調(diào)用DLL動(dòng)態(tài)鏈接庫9. 淺談JavaScript中等號(hào)、雙等號(hào)、 三等號(hào)的區(qū)別10. Python如何進(jìn)行時(shí)間處理
