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

使用Python text_to_font模块开发语录生成器报OSError: cannot open resource

错误触发原因

你遇到的OSError: cannot open resource是word_to_ascii方法加载指定字体文件失败导致的,核心原因有3类:

  • Python字符串默认不会自动解析路径中的~(用户主目录占位符),系统会直接把~/fonts/somefont.ttf当做字面路径查找,无法匹配到实际文件
  • 对应路径下不存在somefont.ttf文件,可能是文件名拼写错误、大小写不匹配、字体文件后缀错误
  • 当前运行脚本的用户没有该字体文件的读取权限
解决方法

按以下步骤排查修复即可:

  1. 展开用户主目录路径
    引入os模块的expanduser方法处理带~的路径,修正后的代码示例:
from quotefancy import get_quote
import os
from text_to_font.transformations import word_to_ascii

a = get_quote(type='text')
# 自动解析~为当前用户主目录实际路径
font_path = os.path.expanduser('~/fonts/somefont.ttf')
print(word_to_ascii(
    phrase=a, 
    font_size=3, 
    kerning=1,
    font_path=font_path  
))
  1. 确认字体文件存在
    打印处理后的font_path路径,检查对应位置是否存在目标字体文件,也可以先替换为系统自带字体的绝对路径测试功能是否正常:
  • Windows系统可测试:C:/Windows/Fonts/msyh.ttc(微软雅黑字体)
  • Linux系统可测试:/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf
  • macOS系统可测试:/Library/Fonts/Arial.ttf
  1. 检查文件读取权限
    如果确认文件存在仍报错,Linux/macOS系统可执行chmod +r 字体文件绝对路径给当前用户添加读取权限。

内容的提问来源于stack exchange,提问作者Sense of Science

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 02:57:03