"""
function:
@Time : 2022/7/4 下午15:14
@Author : simple huang
"""
import os
import yaml
from yaml.loader import SafeLoader
import tarfile
from typing import Any, Text, Dict, List
from shutil import copyfile
import shutil
def check_dir_exists(dir):
"""
接收文件夹路径,如果不存在则新建
Args:
dir: 文件夹路径
Returns:
"""
if not os.path.exists(dir): # os模块判断并创建
os.mkdir(dir)
def walk_files(path,endpoint=".yml"):
"""
接收文件路径,递归列出底下所有固定格式结尾的文件
Args:
path: 文件路径
endpoint: 文件后缀
Returns:
List[files]
"""
file_list = []
for root,dirs,files in os.walk(path):
for file in files:
file_path = os.path.join(root,file)
if file_path.endswith(endpoint):
file_list.append(file_path)
return file_list
def load_yml(
file_path: str
) -> dict:
"""
接收yml文件路径,读取该yml文件,返回字典格式
Args:
file_path: 文件路径
Returns:
dict
"""
with open(file_path, encoding = "utf-8") as f:
results = yaml.load(f, Loader = SafeLoader)
return results
def is_file(
file_path: str
) -> bool:
"""
判断是否为文件
Args:
file_path: 文件路径
Returns:
True
False
"""
if not os.path.isfile(file_path):
return False
else:
return True
def is_tar_gz(
file_path: str
) -> bool:
"""
判断是否为tar.gz文件
Args:
file_path: 文件路径
Returns:
True
False
"""
if not file_path.endswith(".tar.gz"):
return False
else:
return True
def un_targz(
file_path: str,
dst: str
):
"""
解压tar.gz文件 到目标文件夹下面
Args:
file_path: 文件路径
dst: 目标文件夹
Returns:
success: 解压成功
"""
if not is_file(file_path):
return f"{file_path} Not a file !"
if not is_tar_gz(file_path):
return f"{file_path} must be tar.gz file !"
try:
tar = tarfile.open(file_path)
names = tar.getnames()
for name in names:
tar.extract(name, dst)
tar.close()
return "un tar.gz success !"
except:
return f"{file_path} Decompression error !"
def copy_file(
path_read: str ,
path_write: str
):
"""
将path_read目录下面的文件复制到path_write目录下面,保留path_read的目录结构
Args:
path_read: 复制文件夹路径
path_write: 目标文件夹路径
Returns:
"""
names = os.listdir(path_read)
for name in names:
path_read_new = path_read + "\\" + name
path_write_new = path_write + "\\" + name
if os.path.isdir(path_read_new):
if not os.path.exists(path_write_new):
os.mkdir(path_write_new)
copy_file(path_read_new, path_write_new)
else:
copyfile(path_read_new, path_write_new)
def delete_dir(
target_dir: str
):
"""
删除给定目录
Args:
target_dir
Returns:
"""
try:
shutil.rmtree(target_dir)
except:
pass
python 通用函数 持续更新(1、判断文件夹是否存在,不存在则新建 2、递归列出某文件夹底下所有固定格式结尾的文件 3、加载yml文件...)
最新推荐文章于 2024-05-07 09:00:00 发布