遍历目录,查找指定后缀文件
方法一:
import osdef get_files(dir_path,suffix,res):
file_list = os.listdir(dir_path)
for obj in file_list:
new_path = os.path.join(dir_path,obj)
if os.path.isfile(new_path):
if obj.endswith(suffix):
res.append(os.path.join(dir_path,obj))
elif os.path.isdir(new_path):
get_files(new_path,suffix,res)if __name__ == '__main__':
res_list = []
get_files('./','.pyc',res_list)
print(res_list)
方法二:
import osdef get_files(search_dir,suffix):
res = []
for root, dirs, files in os.walk(search_dir):
for file in files:
name,suf = os.path.splitext(file)
if suf == suffix:
print(root)
res.append(os.path.join(root,file))
return resif __name__ == '__main__':
res = get_files('./','.pyc')
print(res)
【遍历目录,查找指定后缀文件】方法三:
from glob import iglobdef get_files(dir_path,suffix,res):
for file in iglob(f"{dir_path}/**/*{suffix}",recursive=True):
res.append(file)if __name__ == '__main__':
res_list = []
get_files('./','.pyc',res_list)
print(res_list)
推荐阅读
- opencv|opencv C++模板匹配的简单实现
- Java|Java基础——数组
- ssh生成公钥秘钥
- 言情成长小说《后来》|目录
- typeScript入门基础介绍
- laravel框架泛解
- JavaScript|JavaScript — 初识数组、数组字面量和方法、forEach、数组的遍历
- JavaScript|JavaScript之DOM增删改查(重点)
- 新一代Python包管理工具
- Java应该在哪里判断List是否为空