You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python管理AZW3、EPUB、MOBI文件:求适配库及实现指定功能

Python处理AZW3/EPUB/MOBI文件:转换与元数据修改

要实现你需要的功能,最可靠的方案是借助Calibre的命令行工具——它原生支持AZW3、EPUB、MOBI等格式的转换与元数据编辑,Python可以通过subprocess模块直接调用这些工具。

前置准备

首先安装Calibre,安装后ebook-convert(格式转换)和ebook-meta(元数据修改)会被添加到系统路径(Windows可能需要手动配置环境变量,或者在代码中指定工具的完整路径)。

函数实现

修改作者信息 set_authors

使用ebook-meta命令覆盖文件的作者元数据:

import subprocess
import os

def set_authors(path_of_file, authors: str):
    if not os.path.exists(path_of_file):
        raise FileNotFoundError(f"文件不存在: {path_of_file}")
    
    # 调用ebook-meta修改作者字段
    try:
        subprocess.run(
            ["ebook-meta", path_of_file, "--author", authors],
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
    except subprocess.CalledProcessError as e:
        raise RuntimeError(f"修改作者失败: {e.stderr}") from e

EPUB转AZW3 convert_epub_to_azw3

调用ebook-convert完成格式转换:

def convert_epub_to_azw3(input_file, output_file):
    if not os.path.exists(input_file):
        raise FileNotFoundError(f"输入文件不存在: {input_file}")
    
    try:
        subprocess.run(
            ["ebook-convert", input_file, output_file],
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
    except subprocess.CalledProcessError as e:
        raise RuntimeError(f"转换失败: {e.stderr}") from e

AZW3转EPUB convert_azw3_to_epub

反转转换方向即可:

def convert_azw3_to_epub(input_file, output_file):
    if not os.path.exists(input_file):
        raise FileNotFoundError(f"输入文件不存在: {input_file}")
    
    try:
        subprocess.run(
            ["ebook-convert", input_file, output_file],
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
    except subprocess.CalledProcessError as e:
        raise RuntimeError(f"转换失败: {e.stderr}") from e

注意事项

  • Windows系统中,如果工具不在系统路径里,需要在命令列表中替换为完整路径,比如["C:\\Program Files\\Calibre2\\ebook-meta.exe", ...]
  • 转换大文件时,subprocess.run会阻塞直到完成,若需要异步处理可以改用subprocess.Popen
  • 可以给ebook-convert添加更多参数(比如调整排版、压缩级别),具体可参考Calibre命令行文档

内容的提问来源于stack exchange,提问作者Rabbit220

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 22:53:02