Python3中如何檢查檔案是否存在?Python教程!
眾所周知,Python版本分為Python2和Python3,那麼你知道Python3中如何檢查檔案是否存在嗎?常用的方法有哪些小編為大家列舉幾種方法。
一、 使用os庫
os庫方法可檢查檔案是否存在,存在返回Ture,不存在返回False,且不需要開啟檔案。
1. os.path.isfile檔案檢查
import os.path
filename='/oldboyedu.com/file.txt'
os.path.isfile(filename)
2. os.path.exists資料夾檢查
import os
a_path='/oldboyedu.com/'
if os.path.exists(a_path):
#do something
3. os.access檔案許可權檢查
import os
filename='/oldboyedu.com/file.txt'
if os.path.isfile(filename) and os.access(filename, os.R_OK):
#do something
二、使用pathlib庫
使用pathlib庫也是一種檢查檔案是否存在的方法,且從Python3.4開始,Python已經把pathlib加入了標準庫,無需安裝,即可直接使用!
1. 檢查檔案是否存在
from pathlib import Path
my_file = Path("/oldboyedu.com/file.txt")
if my_file.is_file():
# file exists
2. 檢查資料夾是否存在
from pathlib import Path
my_file = Path("/oldboyedu.com/file.txt")
if my_file.is_dir():
# directory exists
3. 檔案或資料夾是否存在
from pathlib import Path
my_file = Path("/oldboyedu.com/file.txt")
if my_file.exists():
# path exists
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69952527/viewspace-2756435/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- Python3如何檢查檔案或資料夾是否存在?Python
- Python3檢查檔案是否存在的常用方法!Python
- 檢查LOGO是否存在Go
- python 判斷檔案是否存在Python
- 檢查貨幣是否存在SAP系統中
- python怎麼驗證檔案是否存在Python
- python判斷檔案是否存在等操作Python
- Python判斷一個檔案中的字串是否存在於另外一個檔案中Python字串
- js如何判斷指定的檔案是否存在JS
- 檢查是否存在truncate或者rebuild的索引Rebuild索引
- 判斷檔案中是否存在中文字元字元
- Python檢驗一個檔案是否存在,如果不在就自己填寫內容。Python
- golang判斷檔案是否存在Golang
- vc判斷檔案是否存在
- Python 判斷檔案是否存在的三種方法Python
- 用RMAN備份歸檔日誌時檢查歸檔日誌是否存在
- Python3中檔案處理Python
- Oracle 11g 通過 RMAN 檢查資料檔案、控制檔案、引數檔案的狀態和是否存在壞塊Oracle
- 用 Python 批量檢查 sqlite/db3 檔案是否損壞(qbit)PythonSQLite
- java判斷檔案是否存在並建立檔案Java
- python檢測圖片是否存在指令碼Python指令碼
- javascript如何檢測一個圖片是否存在JavaScript
- python列表中是否存在某個元素Python
- Python3編碼如何實現檔案操作?Python
- js如何建立、刪除或者檢測cookie是否存在JSCookie
- jquery怎麼樣判斷檔案是否存在jQuery
- C# 判斷遠端檔案是否存在C#
- shell 判斷檔案或路徑是否存在
- QTP中如何判斷Excel程式是否存在?QTExcel
- 如何檢查域名解析是否生效?
- 如何檢查是否物理伺服器?伺服器
- 分享實用監控指令碼:使用Shell檢查程式是否存在指令碼
- 使用CHECKSYNTAX命令檢查RMAN指令碼是否存在語法錯誤指令碼
- SQL SERVER 建表table之前,檢查是否有同名的表存在SQLServer
- Android 檢查裝置是否存在 導航欄 NavigationBarAndroidNavigation
- javascript,檢測object物件中是否存在某個屬性JavaScriptObject物件
- XamarinEssentials教程首選項Preferences判斷專案是否存在
- 在Linux中,如何建立、檢查和修復檔案系統?Linux