打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
每日一课 | Python –如何检查文件是否存在
在Python中,我们可以使用os.path.isfile()pathlib.Path.is_file() (Python 3.4)来检查文件是否存在。

1. pathlib

Python 3.4的新功能
from pathlib import Path
 
fname = Path("c:\\test\\abc.txt")
 
print(fname.exists()) # true
 
print(fname.is_file()) # true
 
print(fname.is_dir()) # false
 
dir = Path("c:\\test\\")
 
print(dir.exists()) # true
 
print(dir.is_file()) # false
 
print(dir.is_dir()) # true

如果检查
from pathlib import Path
 
fname = Path("c:\\test\\abc.txt")
 
if fname.is_file():
    print("file exist!")
else:
    print("no such file!")

2. os.path

一个经典的os.path示例。
import os.path
 
fname = "c:\\test\\abc.txt"
 
print(os.path.exists(fname)) # true
 
print(os.path.isfile(fname)) # true
 
print(os.path.isdir(fname)) # false
 
dir = "c:\\test\\"
 
print(os.path.exists(dir)) # true
 
print(os.path.isfile(dir)) # false
 
print(os.path.isdir(dir)) # true

如果检查。
import os.path
 
fname = "c:\\test\\abc.txt"
 
if os.path.isfile(fname):
    print("file exist!")
else:
    print("no such file!")

3.试试:除了

我们还可以使用try except检查文件是否存在。
fname = "c:\\test\\no-such-file.txt"
 
try:
    with open(fname) as file:
        for line in file:
            print(line, end='')
except IOError as e:
    print(e)

输出量
[Errno 2] No such file or directory: 'c:\\test\\no-such-file.txt'

参考文献

  1. pathlib —面向对象的文件系统路径

  2. os.path —常用路径名操作

翻译自: https://mkyong.com/python/python-how-to-check-if-a-file-exists/
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Python学习笔记 | 办公自动化基础之文件和文件夹操作
Python十大文件骚操作!!
分享几个好用到爆的 Python 模块,建议收藏!
python模块系列-OS模块
python
pathlib:优雅的路径处理库
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服