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

ImportError问题:无法从utils模块导入record_to_file函数

问题描述

我在构建基于语音分析的性别检测系统时,尝试从本地utils.py文件导入load_data和record_to_file函数,触发了导入错误。

导入代码

from utils import load_data, record_to_file

报错信息

ImportError                               Traceback (most recent call last)
Cell In[8], line 3
      1 import argparse
      2 import os
----> 3 from utils import load_data, record_to_file
      4 from tensorflow.keras.models import Sequential
      5 from tensorflow.keras.layers import Dense, Dropout

ImportError: cannot import name 'record_to_file' from 'utils' (C:\Users\mamta\GD-VA\utils.py)

已确认utils.py中存在该函数

def record_to_file(filename, duration=5, samplerate=44100, channels=2):
    """Record audio to a WAVE file."""
    print("Recording started...")
    myrecording = sd.rec(int(duration * samplerate), samplerate=samplerate, channels=channels)
    sd.wait()
    sf.write(filename, myrecording, samplerate)
    print("Recording finished.")
排查与解决步骤
  • 确认文件路径与导入范围:
    检查主脚本是否和utils.py在同一目录(C:\Users\mamta\GD-VA\)。如果主脚本在子目录,需用相对导入或把父目录加入Python路径:

    import sys
    sys.path.append("C:\\Users\\mamta\\GD-VA")
    from utils import load_data, record_to_file
    
  • 检查函数定义的有效性:
    确保record_to_file函数没有被包裹在if __name__ == "__main__":这类条件判断里,也没有拼写错误(注意大小写、字符一致性)。同时检查utils.py文件开头是否有语法错误,语法错误会导致后续代码无法正常加载。

  • 排查同名模块冲突:
    避免和Python标准库或第三方库的utils模块冲突,可先打印导入的utils路径确认:

    import utils
    print(utils.__file__)
    

    如果输出不是你的目标文件,改用绝对导入:

    from GD_VA.utils import load_data, record_to_file
    
  • 清理缓存文件:
    删除utils.py所在目录下的__pycache__文件夹,重启Python环境后再尝试导入,避免旧的编译缓存导致修改不生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 13:45:33