Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1586069
  • 博文数量: 2195
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 22079
  • 用 户 组: 普通用户
  • 注册时间: 2020-11-26 14:30
个人简介

更多python、Linux、网络安全学习内容,可移步:www.oldboyedu.com或关注\"老男孩Linux\"公众号

文章分类

全部博文(2195)

文章存档

2024年(45)

2023年(643)

2022年(693)

2021年(734)

2020年(80)

我的朋友

分类: Python/Ruby

2023-04-13 16:34:59

  在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():

  # path exists

阅读(422) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~