您好,登錄后才能下訂單哦!
這篇文章主要講解了Python測試文件是否存在的方法,內(nèi)容清晰明了,對此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會有幫助。
問題
你想測試一個文件或目錄是否存在。
解決方案
使用 os.path
模塊來測試一個文件或目錄是否存在。比如:
>>> import os >>> os.path.exists('/etc/passwd') True >>> os.path.exists('/tmp/spam') False >>>
你還能進(jìn)一步測試這個文件時什么類型的。 在下面這些測試中,如果測試的文件不存在的時候,結(jié)果都會返回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)行文件測試是很簡單的。 在寫這些腳本時,可能唯一需要注意的就是你需要考慮文件權(quán)限的問題,特別是在獲取元數(shù)據(jù)時候。比如:
>>> 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_size PermissionError: [Errno 13] Permission denied: '/Users/guido/Desktop/foo.txt' >>>
看完上述內(nèi)容,是不是對Python測試文件是否存在的方法有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。