文章目录

  • 前言
  • 一、代码展示
  • 二、函数使用方法
  • 总结



前言


在程序运行时,少部分数据可能会被某段代码读写,这时我们往往需要在读写前后确认文件或文件夹是否存在,本文针对该问题,编写了一种确认某路径下是否存在目标文件或文件夹的函数。


一、代码展示

python对于文件的存在判断往往需要多行代码,作者将此代码段整合为一个输出bool型变量的函数,以方便在if判断中能够简易的完成此类判断,提高代码编写效率。

import os

def isexist(name, path=None):
    '''
    
    :param name: 需要检测的文件或文件夹名
    :param path: 需要检测的文件或文件夹所在的路径,当path=None时默认使用当前路径检测
    :return: True/False 当检测的文件或文件夹所在的路径下有目标文件或文件夹时返回Ture,
            当检测的文件或文件夹所在的路径下没有有目标文件或文件夹时返回False
    '''
    if path is None:
        path = os.getcwd()
    if os.path.exists(path + '/' + name):
        print("Under the path: " + path + '\n' + name + " is exist")
        return True
    else:
        if (os.path.exists(path)):
            print("Under the path: " + path + '\n' + name + " is not exist")
        else:
            print("This path could not be found: " + path + '\n')
        return False

二、函数使用方法


输入参数

数据格式

用途

path

字符串(str)

需要检测的文件或文件夹所在的路径

name

字符串(str)

需要检测的文件或文件夹名

输出参数

数据格式

用途

True/False

布尔(bool)

检测存在时返回True,检测不存在时返回False

简介:
isexist() 函数中的path参数为需要检测的文件或文件夹所在的路径,当path=None时默认使用当前路径检测,
name参数为需要检测的文件或文件夹名,推荐函数在if判断中使用。

代码示例:
示例代码1:

import os
# 若当前路径目标文件不存在则创建文件
if not isexist(name='test_file.txt'):
    file = open('./test_file.txt', 'w')
    file.write('textwrite')
    file.close()
# 检测文件是否创建成功
isexist(name='test_file.txt', path='.')

示例代码1输出结果:

Under the path: C:\Users\test\Desktop\PJ
test_file.txt is not exist
Under the path: .
test_file.txt is exist

示例代码2:

import os
# 若当前路径目标文件夹不存在则创建文件夹
if not isexist(name='test_dir'):
    os.makedirs('./test_dir')
# 检测文件夹是否创建成功
isexist(name='test_dir', path='.')

示例代码2输出结果:

Under the path: C:\Users\test\Desktop\PJ
test_dir is not exist
Under the path: .
test_dir is exist

总结


以上就是今天要讲的内容,本文介绍一种简单的确认某路径下是否存在目标文件或文件夹的函数,帮助大家在代码编写时减少一些麻烦。