首页 > 编程语言 > 详细

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

时间:2021-07-21 17:12:07      阅读:22      评论:0      收藏:0      [点我收藏+]

四种方法:

# 第一种 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

 

 
 

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

原文:https://www.cnblogs.com/Revelation/p/15039079.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!