分享

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

 风声之家 2020-10-10
在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:///python/python-how-to-check-if-a-file-exists/

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多