Python3中如何检查文件是否存在?Python教程!
众所周知,中何Python版本分为Python2和Python3,检查教程那么你知道Python3中如何检查文件是文件否存在吗?常用的方法有哪些?老男孩教育为大家列举几种方法。

一、否存 使用os库
os库方法可检查文件是中何否存在,源码库存在返回Ture,检查教程不存在返回False,文件且不需要打开文件。否存
1. os.path.isfile文件检查
import os.path
filename=/oldboyedu.com/file.txt
os.path.isfile(filename)
2. os.path.exists文件夹检查
import os
a_path=/oldboyedu.com/
if os.path.exists(a_path):
#do something
3. os.access文件权限检查
import os
filename=/oldboyedu.com/file.txt
if os.path.isfile(filename) and 中何os.access(filename, os.R_OK):
#do something
二、使用pathlib库
使用pathlib库也是检查教程一种检查文件是否存在的免费源码下载方法,且从Python3.4开始,文件Python已经把pathlib加入了标准库,否存无需安装,中何即可直接使用!
1. 检查文件是检查教程否存在
from pathlib import Path
my_file = Path("/oldboyedu.com/file.txt")
if my_file.is_file():
# file exists
2. 检查文件夹是否存在
from pathlib import Path
my_file = Path("/oldboyedu.com/file.txt")
if my_file.is_dir():
# directory exists
3. 文件或文件夹是香港云服务器否存在
from pathlib import Path
my_file = Path("/oldboyedu.com/file.txt")
if my_file.exists():
本文地址:http://www.bzuk.cn/news/000f8499915.html
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。