#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2022/9/12 21:03 # @Author : old tom # @File : fh_file_path.py # @Project : Futool # @Desc : 文件路径 import pathlib import os import typing class PathNotExistError(Exception): """ 路径不存在 """ def __init__(self, msg=''): Exception.__init__(self, msg) def resolve_2_abs(path) -> pathlib.Path: """ 相对路径解析为绝对路径 :param path: :return: """ return pathlib.Path(path).resolve() def isabs(path): """ 是否绝对路径 :param path: :return: """ return os.path.isabs(path) def exist(path): """ 文件或文件夹是否存在 :param path: :return: """ return os.path.exists(path) def rm_dir(dir_path): """ 删除文件夹,此目录必须为空 :param dir_path: :return: """ pathlib.Path(dir_path).rmdir() def find_file_by_pattern(path, pattern) -> typing.Generator: """ 根据匹配规则查找文件 :param path: 路径 :param pattern: 例:所有txt,*.txt :return: """ return pathlib.Path(path).rglob(pattern) def loop_mk_dir(dir_path, mode=0o777, exist_ok=False): """ 创建文件夹及其子路径 :param dir_path: 文件夹路径 :param mode: 权限 :param exist_ok: 是否覆盖 :return: """ pathlib.Path(dir_path).mkdir(parents=True, mode=mode, exist_ok=exist_ok) def loop_dir(dir_path, file_container: list, filter_fun=None): """ 递归文件夹 :param dir_path: :param file_container: 路径容器 :param filter_fun: 自定义过滤 :return: """ if not exist(dir_path): raise PathNotExistError('目标文件夹不存在') file_list = os.listdir(dir_path) for f in file_list: full_path = os.path.join(dir_path, f) if os.path.isdir(full_path): loop_dir(full_path, file_container, filter_fun) else: if filter_fun: if filter_fun(full_path): file_container.append(full_path) else: file_container.append(full_path) return file_container def is_windows_path(path) -> bool: """ 是否windows路径 :param path: :return: """ return len(str(pathlib.Path(path).drive).rstrip()) > 0 def parent_path_str(path) -> str: """ 父级路径 :param path: :return: """ return str(parent_path(path)) def parent_path(path) -> pathlib.Path: """ 父级路径 :param path: :return: """ return pathlib.Path(path).parent def pwd(): """ 当前路径 :return: """ return pathlib.Path().cwd() def home(): """ home路径 :return: """ return pathlib.Path().home()