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

Python中Matplotlib动画存为MP4报错FileNotFoundError,如何解决?

问题:Matplotlib动画存GIF正常,存MP4报错

代码示例

from matplotlib import pyplot as plt 
import numpy as np 
import matplotlib.animation as animation 
  
fig = plt.figure() 
axis = plt.axes(xlim=(0, 4),  ylim=(-1.5, 1.5)) 
line, = axis.plot([], [], lw=3) 
def animate(frame_number): 
    x = np.linspace(0, 4, 1000) 
    y = np.sin(2 * np.pi * (x - 0.01 * frame_number)) 
    line.set_data(x, y) 
    line.set_color('green') 
    return line, 

anim = animation.FuncAnimation(fig, animate, frames=100,  
                               interval=20, blit=True) 
fig.suptitle('Sine wave plot', fontsize=14) 
anim.save("animation.gif", dpi=300, writer=animation.PillowWriter(fps=25)) # 正常运行

anim.save("animation.mp4", writer = animation.FFMpegWriter(fps=25))# 运行失败

问题描述

上述代码可以正常生成并保存GIF格式的动画,但保存为MP4时触发以下错误:

\AppData\Local\Programs\Python\Python312\Lib\site-packages\matplotlib\animation.py:240, in AbstractMovieWriter.saving(self, fig, outfile, dpi, *args, **kwargs)
...
   1553     self._close_pipe_fds(p2cread, p2cwrite,
   1554                          c2pread, c2pwrite,
   1555                          errread, errwrite)

FileNotFoundError: [WinError 2] 系统找不到指定的文件

原因分析

这个错误本质是Matplotlib找不到FFmpeg工具。FFMpegWriter依赖外部的FFmpeg程序来编码MP4视频,你的系统要么没安装FFmpeg,要么没把它加入系统环境变量,导致Python调用时无法定位到该程序。

解决步骤

    1. 安装FFmpeg
      下载Windows版FFmpeg压缩包,解压到任意路径(比如C:\FFmpeg)。
    1. 添加环境变量
      把FFmpeg解压目录下的bin文件夹路径(比如C:\FFmpeg\bin)添加到系统的PATH环境变量中,添加完成后重启Python编辑器或终端。
    1. 验证安装
      打开命令提示符,输入ffmpeg -version,如果能输出FFmpeg的版本信息,说明安装配置成功。
    1. 备选方案(无需环境变量)
      如果不想配置环境变量,可以在代码里直接指定FFmpeg的可执行文件路径:
    writer = animation.FFMpegWriter(fps=25, executable='C:/FFmpeg/bin/ffmpeg.exe')
    anim.save("animation.mp4", writer=writer)
    

内容的提问来源于stack exchange,提问作者Gооd_Mаn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 04:13:13