Python判断文件/文件夹存在方法

四种方法:

# 第一种 os.path.exists(file_path)

# 第二种 os.path.isfile(file_path)

# 第三种 pathlib模块

# 第四种 os.access(file_path,mode)

# 第五种 try+open() 或者with open()

示例:

import os
import sys

#判断文件是否存在
print(os.getcwd())

# vscode中 python插件不能自动cd到当前目录
file = os.path.join(sys.path[0],"test.txt")

# 第一种 os.path.exists(file_path)
print("os.path.exists method test")
print(os.path.exists(file))
print(os.path.exists("test1.txt"))

# 第二种 os.isfile(file_path)
#这种方法判断文件夹也是一样的
print("os.path.isfile test")
print(os.path.isfile(file))
print(os.path.isfile("test1.txt"))

# 第三种 pathlib
# python3.4后 内建pathlib模块 pythonp2版本需要安装
from pathlib import Path
print("pathlib test")
path = Path(file)
print(path.is_file())
print(path.exists())

# 第四种 os.access(file_path,mode)
"""
os.F_OK: 检查文件是否存在 0;
os.R_OK: 检查文件是否可读 1;
os.W_OK: 检查文件是否可以写入 2;
os.X_OK: 检查文件是否可以执行 3
"""
print("os.access test")
print(os.access(file,0))
print(os.access("test.py",0))

# 第五种
# try + open()

# with open()

运行结果:

os.path.exists method test
True
False
os.path.isfile test
True
False
pathlib test
True
True
os.access test
True
False

 

 
os.makedirs(save_path, exist_ok=True)
 
posted @ 2021-07-21 13:36  是我菜了  阅读(692)  评论(0编辑  收藏  举报