Python中的OS模塊提供了與操作係統進行交互的函數。操作係統屬於Python的標準實用程序模塊。該模塊提供了使用依賴於操作係統的函數的便攜式方法。 os.path模塊是python中OS模塊的子模塊,用於通用路徑名操作。
os.path.exists()
Python中的method方法用於檢查指定的路徑是否存在。此方法還可用於檢查給定的路徑是否引用了打開的文件描述符。
用法: os.path.exists(path)
參數:
path:代表文件係統路徑的path-like對象。 path-like對象是表示路徑的字符串或字節對象。
返回類型:此方法返回布爾型的布爾值。如果路徑存在,則此方法返回True,否則返回False。
代碼1:os.path.exists()方法的使用
# Python program to explain os.path.exists() method
# importing os module
import os
# Specify path
path = '/usr/local/bin/'
# Check whether the specified
# path exists or not
isExist = os.path.exists(path)
print(isExist)
# Specify path
path = '/home/User/Desktop/file.txt'
# Check whether the specified
# path exists or not
isExist = os.path.exists(path)
print(isExist)
輸出:
True False
注意: os.path.exists()
如果未授予對請求的文件執行os.stat()的權限,即使該路徑存在,函數也可能返回False。
參考: https://docs.python.org/3/library/os.path.html
相關用法
- Python os.dup()用法及代碼示例
- Python next()用法及代碼示例
- Python set()用法及代碼示例
- Python object()用法及代碼示例
- Python bytes()用法及代碼示例
- Python os.times()用法及代碼示例
- Python os.chmod用法及代碼示例
- Python hash()用法及代碼示例
- Python os.ftruncate()用法及代碼示例
- Python os.truncate()用法及代碼示例
- Python os.fsdecode()用法及代碼示例
- Python dict pop()用法及代碼示例
- Python os.abort()用法及代碼示例
- Python os.WEXITSTATUS()用法及代碼示例
注:本文由純淨天空篩選整理自ihritik大神的英文原創作品 Python | os.path.exists() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。