重装Python与TensorFlow后无法导入pywrap_tensorflow的问题求助
TensorFlow导入错误:无法从'tensorflow.python'导入'pywrap_tensorflow'
报错信息
ImportError Traceback (most recent call last) Cell In[7], line 1 ----> 1 import tensorflow File c:\Users\LENOVO\AppData\Local\Programs\Python\Python312\Lib\site-packages\tensorflow\__init__.py:40 37 _os.environ.setdefault("ENABLE_RUNTIME_UPTIME_TELEMETRY", "1") 39 # Do not remove this line; See https://github.com/tensorflow/tensorflow/issues/42596 ---> 40 from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow # pylint: disable=unused-import 41 from tensorflow.python.tools import module_util as _module_util 42 from tensorflow.python.util.lazy_loader import KerasLazyLoader as _KerasLazyLoader ImportError: cannot import name 'pywrap_tensorflow' from 'tensorflow.python' (C:\Users\LENOVO\AppData\Roaming\Python\Python312\site-packages\tensorflow\python\__init__.py)
环境信息
- TensorFlow版本:2.18
- Python版本:3.12.7
背景
之前正常使用TensorFlow,为Hugging Face的transformers包执行pip install tf-keras时遇到WinError5(权限拒绝),于是卸载重装了Python和TensorFlow。此后,无论是使用TensorFlow还是transformers库都会出现上述导入错误。
已尝试方案
- 卸载并重新安装TensorFlow
- 卸载并重新安装Python
- 执行强制重装TensorFlow命令:
pip install tensorflow==2.18.0 --force-reinstall - 未安装transformers包,直接导入tensorflow仍出现相同错误
解决建议
清理残留文件与缓存
- 删除以下路径下的TensorFlow文件夹:
C:\Users\LENOVO\AppData\Local\Programs\Python\Python312\Lib\site-packages\tensorflowC:\Users\LENOVO\AppData\Roaming\Python\Python312\site-packages\tensorflow
- 清空pip缓存:执行
pip cache purge
- 删除以下路径下的TensorFlow文件夹:
以管理员权限重装
- 右键点击命令提示符/PowerShell,选择「以管理员身份运行」
- 执行重装命令:
pip install tensorflow==2.18.0
排查路径冲突
- 检查系统环境变量
PATH,确保只有当前Python3.12的Scripts和python.exe路径,删除旧版本Python的残留路径 - 执行
where python和where pip,确认输出路径均指向Python3.12的安装目录
- 检查系统环境变量
使用虚拟环境隔离依赖
- 创建虚拟环境:
python -m venv tf_env - 激活虚拟环境:
tf_env\Scripts\activate - 在虚拟环境内安装TensorFlow:
pip install tensorflow==2.18.0,再尝试导入
- 创建虚拟环境:
验证安装路径
- 执行
pip show tensorflow,查看Location字段是否指向C:\Users\LENOVO\AppData\Local\Programs\Python\Python312\Lib\site-packages - 若路径为
AppData\Roaming,可尝试加--user参数重装:pip install --user tensorflow==2.18.0,或确保安装时未使用--user参数
- 执行
内容的提问来源于stack exchange,提问作者Darshil Pungalia
相关产品推荐
相关产品推荐

