Python3检查文件是否存在的方法

发布时间:2018-08-07 17:22:49

Python3检查文件是否存在的方法

检查文件是否存在的方法,在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

以上列举Python3中检查文件和文件夹的两种常用的方法,适用于Python3相关版本,其他版本略有不同,可以根据实际情况进行设置!

Python3检查文件是否存在的方法

相关推荐