python_自动查找指定目录下的文件或目录的方法
代码如下
import os def find_file(search_path, file_type="file", filename=None, file_startswith=None, file_endswith=None, abspath=False) -> dict:
"""
查找指定目录下所有的文件(不包含以__开头和结尾的文件)或指定格式的文件,若不同目录存在相同文件名,只返回第1个文件的路径
:param search_path: 查找的目录路径
:param file_type: 查找的类型,可缺省,缺省则默认查找文件类型,可输入值:file和dir,file表示文件,dir表示目录
:param filename: 查找名称,精确匹配,可缺省,缺省则返回所有文件或目录,不可与file_startswith或file_endswith组合使用
:param file_startswith: 模糊匹配开头,可缺省,缺省则不匹配,可与file_endswith组合使用
:param file_endswith: 模糊匹配结尾,可缺省,缺省则不匹配
:param abspath: 是否返回绝对路径,默认返回相对路径
:return: 有结果返回dict类型,key为文件名,value为文件路径,无结果返None
"""
filename_path = {}
the_filename_path = {} if abspath:
search_path = os.path.abspath(search_path) if file_type not in ["file", "dir"]:
raise ValueError(f"file_type只能为file或dir,而输入值为{file_type}") def __find_file(_search_path):
# 返回目录所有名称
names = os.listdir(_search_path)
find_flag = False # 如果查找指定文件,找到就停止查找
if filename is not None and (filename in names):
path = os.path.join(_search_path, filename)
if file_type == "file" and os.path.isfile(path):
the_filename_path.setdefault(filename, path)
find_flag = True
elif file_type == "dir" and os.path.isdir(path):
the_filename_path.setdefault(filename, path)
find_flag = True
return find_flag # 如果根目录未找到,在子目录继续查找
for name in names:
# 过滤以__开头和__结尾的目录,以及__init__.py文件
if name.startswith("__") and name.endswith("__") or name == "__init__.py":
continue child_path = os.path.join(_search_path, name) # 如果是文件就保存
if file_type == "file" and os.path.isfile(child_path):
if file_startswith is None and file_endswith is None:
filename_path.setdefault(name, child_path)
# 保存指定结尾的文件
elif file_startswith is not None and file_endswith is None and name.startswith(file_startswith):
filename_path.setdefault(name, child_path)
elif file_startswith is None and file_endswith is not None and name.endswith(file_endswith):
filename_path.setdefault(name, child_path)
elif file_startswith is not None and file_endswith is not None and name.startswith(file_startswith) and name.endswith(file_endswith):
filename_path.setdefault(name, child_path)
continue
if os.path.isdir(child_path):
if file_type == "dir":
if file_startswith is None and file_endswith is None:
filename_path.setdefault(name, child_path)
# 保存指定结尾的文件
elif file_startswith is not None and file_endswith is None and name.startswith(file_startswith):
filename_path.setdefault(name, child_path)
elif file_startswith is None and file_endswith is not None and name.endswith(file_endswith):
filename_path.setdefault(name, child_path)
elif file_startswith is not None and file_endswith is not None and name.startswith(file_startswith) and name.endswith(file_endswith):
filename_path.setdefault(name, child_path) _result = __find_file(child_path)
if _result is True:
return _result result = __find_file(search_path)
if filename is None:
if filename_path:
return filename_path if filename is not None:
if result is True:
return the_filename_path
目录结构
用法演示
if __name__ == '__main__':
# 目录下不存在文件时
start_path = r".\二级目录"
ret = find_file(start_path)
print("目录下不存在文件时:%s" % ret)
assert ret is None print("="*60) start_path = r".\一级目录"
# 查找所有文件或目录
ret = find_file(start_path, file_type="file")
print("查找所有文件:%s" % ret)
assert len(ret) == 4
ret = find_file(start_path, file_type="dir")
print("查找所有目录:%s" % ret)
assert len(ret) == 4 print("="*60) # 查找指定开始的所有文件
ret = find_file(start_path, file_startswith="次级")
print("查找指定开始的文件:%s" % ret)
assert "次级目录1中的文件.py" in ret
ret = find_file(start_path, file_type="file", file_startswith="哈哈")
print("查找指定开始的文件不存在时:%s" % ret)
assert ret is None print("="*60) # 查找指定结尾的所有文件
ret = find_file(start_path, file_endswith="txt")
print("查找指定结尾的文件:%s" % ret)
assert "一级目录的文件.txt" in ret
ret = find_file(start_path, file_type="file", file_endswith="哈哈")
print("查找指定结尾的文件不存在时:%s" % ret)
assert ret is None print("="*60) # 查找指定开头和指定结尾的所有文件
ret = find_file(start_path, file_startswith="次级", file_endswith="txt")
print("查找指定开头和指定结尾的所有文件:%s" % ret)
assert "次级目录2中的文件.txt" == list(ret.keys())[0]
ret = find_file(start_path, file_startswith="呵呵", file_endswith="txt")
print("查找指定开始不存在,指定结尾存在时:%s" % ret)
assert ret is None
ret = find_file(start_path, file_startswith="次级", file_endswith="哈哈")
print("查找指定开始存在,指定结尾不存在时:%s" % ret)
assert ret is None
ret = find_file(start_path, file_startswith="呵呵", file_endswith="哈哈")
print("查找指定开始和指定结尾都不存在时:%s" % ret)
assert ret is None print("="*60) # 查找指定开始的所有文件
ret = find_file(start_path, file_type="dir", file_startswith="次级")
print("查找指定开始的文件:%s" % ret)
assert "次级目录1中的三级目录" in ret
ret = find_file(start_path, file_type="dir", file_startswith="哈哈")
print("查找指定开始的文件不存在时:%s" % ret)
assert ret is None print("="*60) # 查找指定结尾的所有目录
ret = find_file(start_path, file_type="dir", file_endswith="目录")
print("查找指定结尾的目录:%s" % ret)
assert len(ret) == 2
ret = find_file(start_path, file_type="dir", file_endswith="哈哈")
print("查找指定结尾的目录不存在时:%s" % ret)
assert ret is None print("="*60) # 查找指定开头和指定结尾的所有目录
ret = find_file(start_path, file_type="dir", file_startswith="次级", file_endswith="目录")
print("查找指定开头和指定结尾的所有文件:%s" % ret)
assert "次级目录2中的目录" in ret
ret = find_file(start_path, file_type="dir", file_startswith="呵呵", file_endswith="目录")
print("查找指定开始不存在,指定结尾存在时:%s" % ret)
assert ret is None
ret = find_file(start_path, file_type="dir", file_startswith="次级", file_endswith="哈哈")
print("查找指定开始存在,指定结尾不存在时:%s" % ret)
assert ret is None
ret = find_file(start_path, file_type="dir", file_startswith="呵呵", file_endswith="哈哈")
print("查找指定开始和指定结尾都不存在时:%s" % ret)
assert ret is None print("="*60) # 查找指定文件
ret = find_file(start_path, file_type="file", filename="三级目录中的文件.yaml")
print("查找指定文件:%s" % ret)
assert len(ret) == 1
ret = find_file(start_path, file_type="file", filename="asd")
print("查找不存在的文件:%s" % ret)
assert ret is None
ret = find_file(start_path, file_type="file", filename="次级目录1中的三级目录")
print("以文件类型去查找已存在文件:%s" % ret)
assert ret is None print("=" * 60) # 查找指定目录
ret = find_file(start_path, file_type="dir", filename="次级目录1中的三级目录")
print("查找指定目录:%s" % ret)
assert len(ret) == 1
ret = find_file(start_path, file_type="dir", filename="asd")
print("查找不存在的目录:%s" % ret)
assert ret is None
ret = find_file(start_path, file_type="dir", filename="三级目录中的文件.yaml")
print("以目录类型去查找已存在文件:%s" % ret)
assert ret is None
演示结果
python_自动查找指定目录下的文件或目录的方法的更多相关文章
- 初识TypeScript:查找指定路径下的文件按类型生成json
如果开发过node.js的话应该对js(javascript)非常熟悉,TypeScript(以下简称ts)是js的超集. 下面是ts的官网: https://www.tslang.cn/ 1.环境配 ...
- 9.proc目录下的文件和目录详解
1./proc目录下的文件和目录详解 /proc:虚拟目录.是内存的映射,内核和进程的虚拟文件系统目录,每个进程会生成1个pid,而每个进程都有1个目录. /proc/Version:内核版本 /pr ...
- 8.var目录下的文件和目录详解
1./var目录下的文件和目录详解. /var (该目录存放的是不断扩充且经常修改的目录,包括各种日志文件或者pid文件,存放linux的启动日志和正在运行的程序目录(变化的目录:一般是日志文件,ca ...
- Golang获取目录下的文件及目录信息
一.获取当前目录下的文件或目录信息(不包含多级子目录) func main() { pwd,_ := os.Getwd() //获取当前目录 //获取文件或目录相关信息 fileInfoList ...
- C#递归搜索指定目录下的文件或目录
诚然可以使用现成的Directory类下的GetFiles.GetDirectories.GetFileSystemEntries这几个方法实现同样的功能,但请相信我不是蛋疼,原因是这几个方法在遇上[ ...
- 6.etc目录下重要文件和目录详解
1./etc/下的重要的配置文件 /etc(二进制软件包的 yum /rpm 安装的软件和所有系统管理所需要的配置文件和子目录.还有安装的服务的启动命令也放置在此处) /etc/sysconfig/n ...
- .gitignore排除(不忽略)二级以上目录下的文件或目录
在.gitignore中,结合使用/*和!filename的语法,可以达到除特定文件或目录外全部忽略的目的.但当希望不忽略的文件或目录在二级或多级目录下时,如果这样写 /* !/sub/subsub/ ...
- 使用File类列出指定位置下的文件及目录信息
public static void main(String [] args) { File f=new File("C:"); File [] fl=f.listFiles(); ...
- AIX查询当前目录下各文件及目录大小
AIX下要查询某个目录下各个文件或目录的占用空间大小 可以对du命令增加一个别名alias 放在~/.profile里 alias dus='du -sg ./* |sort' s表示文件和目录都是显 ...
随机推荐
- 编译安装nginx 1.16
准备源码包,并解压,创建nginx用户 [root@slave-master ~]# tar xf nginx-1.16.0.tar.gz [root@slave-master ~]# useradd ...
- t01_docker安装TiDB
Docker环境安装TiDB,在官方说明的基础上补充了几个细节,安装记录如下 个人环境-vbox上安装centos7.4系统 CPU:12核24线程,分配给虚拟机12线程 MEM: 48G,分配给虚拟 ...
- Spring Boot项目的不同启动方式
方式一: 直接通过IntelliJ IDEA启动,直接执行Spring Boot项目的main()方法. 方法二: 将项目打包成jar包,首先需要在pom.xml文件的根节点下添加如下配置: < ...
- [BUUCTF]PWN18——bjdctf_2020_babystack
[BUUCTF]PWN18--bjdctf_2020_babystack 附件 步骤: 例行检查,64位,开启了nx保护 试运行一下程序 大概了解程序的执行过程后用64位ida打开,shift+f12 ...
- Google Earth Engine 中的位运算
Google Earth Engine中的位运算 按位运算是编程中一个难点,同时也是在我们后续处理影像数据,尤其要使用影像自带的波段比如QA波段经常会用到的一个东西.通过按位运算我们可以筛选出我们想要 ...
- 如何高效地把Spring boot学到能干活的程度
Spring boot要学什么?要学到什么程度?以及相关的学习方法是什么?这些很难量化,但极好形容:需要学到能帮你找到一份工作的程度. 任何脱离工作脱离实际的学习,都是没有意义的.比如程序员运行通 ...
- 介绍下Shell中的${}、##和%%使用范例,本文给出了不同情况下得到的结果。
介绍下Shell中的${}.##和%%使用范例,本文给出了不同情况下得到的结果.假设定义了一个变量为:代码如下:file=/dir1/dir2/dir3/my.file.txt可以用${ }分别替换得 ...
- ACwing1015. 摘花生
题目: Hello Kitty想摘点花生送给她喜欢的米老鼠. 她来到一片有网格状道路的矩形花生地(如下图),从西北角进去,东南角出来. 地里每个道路的交叉点上都有种着一株花生苗,上面有若干颗花生,经过 ...
- HDZ城市行深圳站|AIoT时代,如何抓住智联生活的战略机会点?
摘要:2021年12月24日,HDZ城市行深圳站:AIoT引爆全场景应用新机会(智联生活专场)圆满落幕. 2021年12月24日,HDZ城市行深圳站:AIoT引爆全场景应用新机会(智联生活专场)圆满落 ...
- 分享一下java需要的一些技术
1.前言 you are 大哥,老衲很佩服你们_.还是一样的,有我联系方式的人,哪些半吊子不知道要学习哪些技术,一天让我整知识点,老衲也有事情做的,哪有那么多时间来一直搞知识点啊,我的博客更新很慢的, ...