網(wǎng)站首頁 編程語言 正文
Python 操作文件時,我們一般要先判斷指定的文件或目錄是否存在,不然容易產(chǎn)生異常。
1.文件
# 是否存在 import os os.path.exists(test_file.txt)
# 是不是文件 import os os.path.isfile("test-data")
# 是不是文件 from pathlib import Path my_file = Path("/path/to/file") my_file.is_file()
2.文件夾
# 是否存在 import os os.path.exists(test_dir)
# 是不是文件夾 from pathlib import Path my_file = Path("/path/to/file") my_file.is_dir()
# 是否存在 from pathlib import Path my_file = Path("/path/to/file") my_file.exists()
3.補充
例如我們可以使用 os 模塊的 os.path.exists() 方法來檢測文件是否存在:
import os.path os.path.isfile(fname)
如果你要確定他是文件還是目錄,從 Python 3.4 開始可以使用 pathlib 模塊提供的面向?qū)ο蟮姆椒?(Python 2.7 為 pathlib2 模塊):
from pathlib import Path my_file = Path("/path/to/file") if my_file.is_file(): ? ? # 指定的文件存在
檢測是否為一個目錄:
if my_file.is_dir(): ? ? # 指定的目錄存在
如果要檢測路徑是一個文件或目錄可以使用 exists() 方法:
if my_file.exists(): ? ? # 指定的文件或目錄存在
在 try 語句塊中你可以使用 resolve() 方法來判斷:
try: ? ? my_abs_path = my_file.resolve() except FileNotFoundError: ? ? # 不存在 else: ? ? # 存在
原文鏈接:https://blog.csdn.net/weixin_44493841/article/details/123553838
相關(guān)推薦
- 2023-09-17 Could not initialize class net.sf.cglib.beans.Bean
- 2022-08-11 boost.asio框架系列之調(diào)度器io_service_C 語言
- 2022-07-08 C#使用GDI+實現(xiàn)生成驗證碼_C#教程
- 2022-09-25 什么是模板引擎(web)?常見的模板引擎有哪些?thymeleaf的常用指令介紹
- 2022-04-21 Docker容器跨主機通信overlay網(wǎng)絡(luò)的解決方案_docker
- 2022-07-14 浮點數(shù)乘法和整形乘除法的效率經(jīng)驗比較_C 語言
- 2022-06-04 C++求解二叉樹的下一個結(jié)點問題_C 語言
- 2022-09-09 python定義函數(shù)如何判斷年份是否為閏年_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支