if not is_tool_available('7z'):
possible_paths = [r"D:\InstallProgram\7-Zip\7z.exe"]
for p in possible_paths:
if os.path.exists(p):
SEVEN_ZIP_PATH = p
break
def get_unique_filename(filepath):
"""如果文件已存在,生成一个新的唯一文件名 (例如 file(1).pdf)"""
if not os.path.exists(filepath):
return filepath
def flatten_output_directory(output_dir):
"""
将 output_dir 下所有子文件夹中的文件移动到 output_dir 根目录
并删除空的子文件夹
"""
if not os.path.exists(output_dir):
return
复制代码
# 遍历目录树
for root, dirs, files in os.walk(output_dir, topdown=False):
# 跳过根目录本身
if root == output_dir:
continue
# 移动文件到根目录
for filename in files:
src_path = os.path.join(root, filename)
dst_path = os.path.join(output_dir, filename)
# 处理文件名冲突
dst_path = get_unique_filename(dst_path)
try:
shutil.move(src_path, dst_path)
# print(f" 移动文件: {filename} 到根目录")
except Exception as e:
print(f" 移动文件失败 {filename}: {e}")
# 删除空文件夹 (os.walk topdown=False 保证先处理子目录)
try:
if not os.listdir(root): # 如果文件夹为空
os.rmdir(root)
except Exception as e:
pass # 忽略删除错误
def extract_pdf_from_zip(zip_path, output_dir):
"""从 zip 文件中提取 PDF (支持 GBK 编码文件名)"""
try:
with zipfile.ZipFile(zip_path, 'r', metadata_encoding='gbk') as z:
for file_info in z.infolist():
if file_info.is_dir():
continue
if file_info.filename.lower().endswith('.pdf'):
filename = os.path.basename(file_info.filename)
if not filename or not filename.strip():
continue
target_path = os.path.join(output_dir, filename)
target_path = get_unique_filename(target_path)
try:
with z.open(file_info) as source, open(
target_path, 'wb') as target:
shutil.copyfileobj(source, target)
except Exception as e:
print(f" 提取 ZIP 中的 PDF 失败 {filename}: {e}")
except Exception as e:
print(f"错误: 无法打开或解压 ZIP 文件 {zip_path}: {e}")
def extract_pdf_from_tar(tar_path, output_dir):
"""从 tar/tar.gz 文件中提取 PDF"""
mode = 'r:gz' if tar_path.endswith('.gz') else 'r'
try:
with tarfile.open(tar_path, mode) as t:
for member in t.getmembers():
if member.isfile() and member.name.lower().endswith('.pdf'):
filename = os.path.basename(member.name)
if filename:
target_path = os.path.join(output_dir, filename)
target_path = get_unique_filename(target_path)
with t.extractfile(member) as source, open(
target_path, 'wb') as target:
shutil.copyfileobj(source, target)
except Exception as e:
print(f"错误: 无法解压 {tar_path}: {e}")