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

macOS导入matplotlib报错:TypeError预期str/bytes/os.PathLike而非PosixPath

macOS Monterey 12.6 + Anaconda Python3.9.13下matplotlib导入报错解决

报错场景与详情

在macOS Monterey 12.6系统的Anaconda环境(Python版本3.9.13)中,执行import matplotlib时触发如下错误:

$ python
Python 3.9.13 (main, Aug 25 2022, 18:29:29) 
[Clang 12.0.0 ] :: Anaconda, Inc. on darwin

>>> import matplotlib
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/opt/anaconda3/lib/python3.9/site-packages/matplotlib/__init__.py", line 876, in <module>
        rcParamsDefault = _rc_params_in_file(
      File "/opt/anaconda3/lib/python3.9/site-packages/matplotlib/__init__.py", line 778, in _rc_params_in_file
        with _open_file_or_url(fname) as fd:
      File "/opt/anaconda3/lib/python3.9/contextlib.py", line 119, in __enter__
        return next(self.gen)
      File "/opt/anaconda3/lib/python3.9/site-packages/matplotlib/__init__.py", line 751, in _open_file_or_url
        fname = os.path.expanduser(fname)
      File "/opt/anaconda3/lib/python3.9/posixpath.py", line 231, in expanduser
        path = os.fspath(path)
    TypeError: expected str, bytes or os.PathLike object, not PosixPath

解决方法

1. 降级matplotlib到兼容版本

该错误源于高版本matplotlib与Python3.9的路径处理逻辑不兼容,降级到3.5.3版本可直接解决:

# 使用conda安装
conda install matplotlib==3.5.3 -y

# 或使用pip安装
pip install matplotlib==3.5.3 --force-reinstall

2. 手动修改matplotlib初始化文件

找到Anaconda环境中的matplotlib初始化文件(路径:/opt/anaconda3/lib/python3.9/site-packages/matplotlib/__init__.py),定位到_open_file_or_url函数内的fname = os.path.expanduser(fname)行,修改为:

fname = os.path.expanduser(str(fname))

将PosixPath对象转为字符串后再处理,保存文件后重新导入matplotlib即可生效。

3. 更新Anaconda环境修复依赖

尝试更新整个Anaconda环境,自动修复依赖兼容问题:

conda update --all -y

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:15:45