日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

python如何判斷文件存在方式_python

作者:JAPAN_is_shit ? 更新時(shí)間: 2022-11-03 編程語(yǔ)言

前言

判斷文件是否存在在實(shí)際應(yīng)用中用的非常多,下面我們來(lái)歸納一下檢查文件、文件夾是否存在的各種操作

一.檢查文件夾/文件是否存在

1. os.path.exists()

文件夾,文件均可,文件無(wú)后綴時(shí)會(huì)和文件夾混淆


# 包括文件和文件夾,導(dǎo)入os.path
import os.path

ret_file = r'C:\Users\Administrator\Desktop\1.xlsx'
# 1  os.path加函數(shù)方法
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()

需要單獨(dú)判斷

import os.path

ret_file = r'C:\Users\Administrator\Desktop\1.xlsx'
#  分開(kāi)做判斷
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()

文件夾,文件均可,文件無(wú)后綴時(shí)會(huì)和文件夾混淆

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文件是否可寫(xiě)
    # res = os.access(ret_file, os.W_OK)
    # os.X_OK文件是否可執(zhí)行
    # res = os.access(ret_file, os.X_OK)

    return res

4. 異常判斷

只能判斷文件

#  直接讀取文件,根據(jù)是否報(bào)錯(cuò)來(lái)判斷文件是否存在(不能讀取文件夾)
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匿名函數(shù)(擴(kuò)展)

import os.path
import os
#lambda 方法,這里只寫(xiě)一種os.path.exists()方式實(shí)現(xiàn)
file_exists = lambda file: os.path.exists(file)

總結(jié)

判斷文件不存在后,按照慣例,下一步應(yīng)該是新建文件、文件夾,然后再進(jìn)行對(duì)文件、文件夾的操作

原文鏈接:https://blog.csdn.net/qq_43504837/article/details/126773714

欄目分類(lèi)
最近更新