每日一课 | Python –如何检查文件是否存在

整理 | 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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值