网络编程
位置:首页>> 网络编程>> Python编程>> python如何判断文件存在方式

python如何判断文件存在方式

作者:JAPAN_is_shit  发布时间:2023-01-23 12:58:37 

标签:python,判断文件,存在方式

前言

判断文件是否存在在实际应用中用的非常多,下面我们来归纳一下检查文件、文件夹是否存在的各种操作

一.检查文件夹/文件是否存在

1. os.path.exists()

文件夹,文件均可,文件无后缀时会和文件夹混淆


# 包括文件和文件夹,导入os.path
import os.path

ret_file = r'C:\Users\Administrator\Desktop\1.xlsx'
# 1  os.path加函数方法
def file_exists(ret_file):
   # 分不清是文件和文件夹
   res = os.path.exists(ret_file)
   return res
result = file_exists(ret_file)
print(result)

2. os.path.isfile()和os.path.isdir()

需要单独判断

import os.path

ret_file = r'C:\Users\Administrator\Desktop\1.xlsx'
#  分开做判断
def file_exists(ret_file):
   # 判断文件
   res1 = os.path.isfile(ret_file)
   # 判断文件夹
   res2 = os.path.isdir(ret_file)
   return (res1,res2)
result = file_exists(ret_file)
print(result)

3. os.access()

文件夹,文件均可,文件无后缀时会和文件夹混淆

import os
ret_file = r'C:\Users\Administrator\Desktop\1.xlsx'
def file_exists(ret_file):
   # # os.F_OK文件是否存在
   res = os.access(ret_file, os.F_OK)
   # # os.R_OK文件是否可读
   # res = os.access(ret_file, os.R_OK)
   # # os.W_OK文件是否可写
   # res = os.access(ret_file, os.W_OK)
   # os.X_OK文件是否可执行
   # res = os.access(ret_file, os.X_OK)

return res

4. 异常判断

只能判断文件

#  直接读取文件,根据是否报错来判断文件是否存在(不能读取文件夹)
def file_exists(ret_file):
   try:
       # f = open(ret_file)
       # f.close()
       with open(ret_file) as f:
           pass
   except IOError:
       return False
   else:
       return True

5. lambda匿名函数(扩展)

import os.path
import os
#lambda 方法,这里只写一种os.path.exists()方式实现
file_exists = lambda file: os.path.exists(file)

来源:https://blog.csdn.net/qq_43504837/article/details/126773714

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com