feat: 新增银行卡检查插件及相关依赖与配置文件
This commit is contained in:
@@ -0,0 +1,217 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""文件与文件夹(对应影刀 file / dir 组指令):判断存在、建目录、读写文本、复制移动删除、遍历、等文件。
|
||||
|
||||
设计取舍:只封「高频且容易写错的小动作」(编码回退、目标目录自动创建、等文件落地),
|
||||
不重复造 pandas / openpyxl / shutil 的轮子。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import fnmatch
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import List, Optional, Union
|
||||
|
||||
PathLike = Union[str, os.PathLike]
|
||||
|
||||
# 读文本时的编码回退顺序(Windows 上 Excel 导出的 csv/txt 常是 GBK)
|
||||
_TEXT_ENCODINGS = ("utf-8-sig", "gbk")
|
||||
|
||||
|
||||
# ==================== 判断 / 创建 ====================
|
||||
def exists(path: PathLike) -> bool:
|
||||
"""路径是否存在(文件或文件夹;影刀「IF 文件存在」)。"""
|
||||
return os.path.exists(str(path))
|
||||
|
||||
|
||||
def file_exists(path: PathLike) -> bool:
|
||||
"""是否是已存在的文件(不含目录)。"""
|
||||
return os.path.isfile(str(path))
|
||||
|
||||
|
||||
def dir_exists(path: PathLike) -> bool:
|
||||
"""是否是已存在的文件夹。"""
|
||||
return os.path.isdir(str(path))
|
||||
|
||||
|
||||
def ensure_dir(path: PathLike) -> str:
|
||||
"""确保目录存在(不存在则递归创建),返回绝对路径。"""
|
||||
p = os.path.abspath(str(path))
|
||||
os.makedirs(p, exist_ok=True)
|
||||
return p
|
||||
|
||||
|
||||
def make_dir(parent: PathLike, name: str = "") -> str:
|
||||
"""创建文件夹(影刀「创建文件夹」):parent 下建 name,name 为空则直接创建 parent。"""
|
||||
target = os.path.abspath(os.path.join(str(parent), str(name))) if str(name) else os.path.abspath(str(parent))
|
||||
os.makedirs(target, exist_ok=True)
|
||||
return target
|
||||
|
||||
|
||||
# ==================== 读写文本 ====================
|
||||
def read_text(path: PathLike, encoding: Optional[str] = None) -> str:
|
||||
"""读文本文件。encoding 为空时依次尝试 UTF-8(带BOM) → GBK。
|
||||
|
||||
中文路径、GBK 编码的 csv/log 都能直接读,不用每次手写 try/except。
|
||||
"""
|
||||
p = str(path)
|
||||
if not os.path.isfile(p):
|
||||
raise RuntimeError(f"文件不存在:{p}")
|
||||
if encoding:
|
||||
return Path(p).read_text(encoding=encoding)
|
||||
last_err: Optional[Exception] = None
|
||||
for enc in _TEXT_ENCODINGS:
|
||||
try:
|
||||
return Path(p).read_text(encoding=enc)
|
||||
except UnicodeDecodeError as e:
|
||||
last_err = e
|
||||
raise RuntimeError(f"无法识别文本编码(试过 {_TEXT_ENCODINGS}):{p}({last_err})")
|
||||
|
||||
|
||||
def write_text(path: PathLike, text: str, encoding: str = "utf-8",
|
||||
append: bool = False) -> str:
|
||||
"""写文本文件(自动创建父目录),返回绝对路径。"""
|
||||
p = os.path.abspath(str(path))
|
||||
parent = os.path.dirname(p)
|
||||
if parent:
|
||||
os.makedirs(parent, exist_ok=True)
|
||||
with open(p, "a" if append else "w", encoding=encoding, newline="") as f:
|
||||
f.write("" if text is None else str(text))
|
||||
return p
|
||||
|
||||
|
||||
def append_line(path: PathLike, text: str, encoding: str = "utf-8") -> str:
|
||||
"""追加一行(自动补换行)。"""
|
||||
return write_text(path, str(text) + "\n", encoding=encoding, append=True)
|
||||
|
||||
|
||||
# ==================== 复制 / 移动 / 删除 ====================
|
||||
def copy(src: PathLike, dst: PathLike, overwrite: bool = True) -> str:
|
||||
"""复制文件或文件夹;dst 是已存在目录时把 src 放进去。返回目标路径。"""
|
||||
s, d = str(src), str(dst)
|
||||
if not os.path.exists(s):
|
||||
raise RuntimeError(f"源路径不存在:{s}")
|
||||
if os.path.isdir(d):
|
||||
d = os.path.join(d, os.path.basename(s.rstrip("\\/")))
|
||||
parent = os.path.dirname(os.path.abspath(d))
|
||||
if parent:
|
||||
os.makedirs(parent, exist_ok=True)
|
||||
if os.path.exists(d) and not overwrite:
|
||||
raise RuntimeError(f"目标已存在且 overwrite=False:{d}")
|
||||
if os.path.isdir(s):
|
||||
shutil.copytree(s, d, dirs_exist_ok=overwrite)
|
||||
else:
|
||||
shutil.copy2(s, d)
|
||||
return os.path.abspath(d)
|
||||
|
||||
|
||||
def move(src: PathLike, dst: PathLike, overwrite: bool = True) -> str:
|
||||
"""移动/重命名文件或文件夹;dst 是已存在目录时移入该目录。返回目标路径。"""
|
||||
s, d = str(src), str(dst)
|
||||
if not os.path.exists(s):
|
||||
raise RuntimeError(f"源路径不存在:{s}")
|
||||
if os.path.isdir(d):
|
||||
d = os.path.join(d, os.path.basename(s.rstrip("\\/")))
|
||||
parent = os.path.dirname(os.path.abspath(d))
|
||||
if parent:
|
||||
os.makedirs(parent, exist_ok=True)
|
||||
if os.path.exists(d):
|
||||
if not overwrite:
|
||||
raise RuntimeError(f"目标已存在且 overwrite=False:{d}")
|
||||
delete(d)
|
||||
shutil.move(s, d)
|
||||
return os.path.abspath(d)
|
||||
|
||||
|
||||
def delete(path: PathLike, missing_ok: bool = True) -> bool:
|
||||
"""删除文件或文件夹(递归)。返回是否真的删掉了东西。"""
|
||||
p = str(path)
|
||||
if not os.path.exists(p):
|
||||
if missing_ok:
|
||||
return False
|
||||
raise RuntimeError(f"路径不存在:{p}")
|
||||
if os.path.isdir(p):
|
||||
shutil.rmtree(p)
|
||||
else:
|
||||
os.remove(p)
|
||||
return True
|
||||
|
||||
|
||||
# ==================== 遍历 / 等待 ====================
|
||||
def list_files(folder: PathLike, pattern: str = "*", recursive: bool = False,
|
||||
ext: Union[str, List[str], None] = None) -> List[str]:
|
||||
"""列出文件(返回绝对路径,按名称排序)。
|
||||
|
||||
Args:
|
||||
pattern: 文件名通配符,如 "*.xlsx"、"工资*"。
|
||||
recursive: 是否递归子目录。
|
||||
ext: 扩展名过滤,如 ".xlsx" 或 [".xlsx", ".xls"](大小写不敏感)。
|
||||
"""
|
||||
folder = str(folder)
|
||||
if not os.path.isdir(folder):
|
||||
return []
|
||||
exts = None
|
||||
if ext:
|
||||
exts = tuple(([ext] if isinstance(ext, str) else list(ext)))
|
||||
exts = tuple((e if e.startswith(".") else "." + e).lower() for e in exts)
|
||||
|
||||
out: List[str] = []
|
||||
if recursive:
|
||||
for root, _dirs, files in os.walk(folder):
|
||||
for name in files:
|
||||
if not fnmatch.fnmatch(name, pattern):
|
||||
continue
|
||||
if exts and not name.lower().endswith(exts):
|
||||
continue
|
||||
out.append(os.path.join(root, name))
|
||||
else:
|
||||
for name in os.listdir(folder):
|
||||
full = os.path.join(folder, name)
|
||||
if not os.path.isfile(full):
|
||||
continue
|
||||
if not fnmatch.fnmatch(name, pattern):
|
||||
continue
|
||||
if exts and not name.lower().endswith(exts):
|
||||
continue
|
||||
out.append(full)
|
||||
out.sort()
|
||||
return out
|
||||
|
||||
|
||||
def newest_file(folder: PathLike, pattern: str = "*", recursive: bool = False) -> Optional[str]:
|
||||
"""目录里最新的文件(按修改时间),没有返回 None(下载目录里取最新导出文件时用)。"""
|
||||
files = list_files(folder, pattern=pattern, recursive=recursive)
|
||||
if not files:
|
||||
return None
|
||||
return max(files, key=lambda p: os.path.getmtime(p))
|
||||
|
||||
|
||||
def wait_file(path: PathLike, timeout: float = 30.0, interval: float = 0.5,
|
||||
min_size: int = 1) -> bool:
|
||||
"""等待文件出现且大小稳定(>= min_size),超时返回 False。用于等下载/导出落地。"""
|
||||
p = str(path)
|
||||
deadline = time.time() + max(0.0, float(timeout))
|
||||
while True:
|
||||
try:
|
||||
if os.path.isfile(p) and os.path.getsize(p) >= max(0, int(min_size)):
|
||||
time.sleep(0.2) # 再确认一次,避免读到写了一半的文件
|
||||
if os.path.isfile(p) and os.path.getsize(p) >= max(0, int(min_size)):
|
||||
return True
|
||||
except OSError:
|
||||
pass
|
||||
if time.time() >= deadline:
|
||||
return False
|
||||
time.sleep(max(0.05, float(interval)))
|
||||
|
||||
|
||||
def wait_file_gone(path: PathLike, timeout: float = 30.0, interval: float = 0.5) -> bool:
|
||||
"""等待文件消失(如临时锁文件释放),超时返回 False。"""
|
||||
p = str(path)
|
||||
deadline = time.time() + max(0.0, float(timeout))
|
||||
while True:
|
||||
if not os.path.exists(p):
|
||||
return True
|
||||
if time.time() >= deadline:
|
||||
return False
|
||||
time.sleep(max(0.05, float(interval)))
|
||||
Reference in New Issue
Block a user