Python使用pathlib模块来判断文件是否存在

 剑鱼论坛 发表于 2020年01月27日 Python  563
剑鱼论坛
LV 8 研究生
最后在线:2年前
加入时间:5年前
主帖:143  跟帖:100

Python语言中我们要判断某个文件是否存在,可以使用pathlib模块,具体的使用方法演示如下:

首先导入pathlib模块:

import pathlib

然后,假设我们要判断文件“test.txt”是否存在,那么先要执行以下语句:

path = pathlib.Path("test.txt")

接着我们就可以来判断了,如下:

path.exists()

执行以上语句就会输出判断结果,如果文件存在会输出“True”,否则会输出“False”。

进一步,我们还可以判断是否是文件:

path.is_file()

如果某个路径是一个文件的话,则会输出“True”,否则会输出“False”。

您可以试着将上面的“test.txt”替换成某个文件夹,is_file执行后会输出“False”。

论坛主帖
288
论坛跟帖
316
在线访客
0
今日主帖
0
今日跟帖
0
今日注册
0
89
http://jianyuluntan.com/gentie.html
http://jianyuluntan.com/postzan.html
http://jianyuluntan.com/postcai.html
http://jianyuluntan.com/postshoucang.html
http://jianyuluntan.com/gentiezan.html
http://jianyuluntan.com/gentiecai.html
http://jianyuluntan.com/huifu.html
http://jianyuluntan.com/xiugai.html
http://jianyuluntan.com/shanchugentie.html
1
XzA=
1
© 2019 - 2024 剑鱼论坛 版权所有
Powered by JianYuLunTan
剑鱼论坛 976666861
http://jianyuluntan.com/feedback.html
http://jianyuluntan.com/qiandao.html
http://jianyuluntan.com/denglu.html
0
http://jianyuluntan.com/adenglu.html
0
剑鱼论坛