OSError when importing torch in Python script

Hello, to whom it concerns

I have stumbled upon a roadblock trying to run a Python script that uses PyTorch. Needless to say, the error message is being quite stubborn when I try to import the torch module. Here’s the error message I’m seeing:

“G:\Project Raphael\env\Lib\site-packages\torch_init_.py”, line 110, in
os.add_dll_directory(dll_path)
File “”, line 1125, in add_dll_directory
OSError: [WinError 87] The parameter is incorrect: ‘G:Library\bin’

I’m using Python version 3.12.3 and PyTorch version 2.3.0 on Windows 11. I’ve tried setting the dll_path to 'G:\Project Raphael\.venv\Lib\site-packages\torch\lib', which is where my torch package is installed, but that did not change the outcome.

Snippet of the problem:

Add DLL directory before importing torch

dll_path = r’G:\Project Raphael.venv\Lib\site-packages\torch\lib’
if os.path.exists(dll_path):
os.environ[‘PATH’] = dll_path + os.pathsep + os.environ[‘PATH’]
print(f"Successfully added DLL directory: {dll_path}“)
else:
print(f"Warning: The DLL path ‘{dll_path}’ does not exist”)

Now import torch

import torch

I resolved the issue by downgrading python to Python 3.9.16. After digging further into lots of forums. There was a member that presented a possible solution. I am not exactly sure but from the explanation of the forums I read the finger was pointed at ‘Python 3.12’ But I just wanted to put this here so if anyone else has a similar issue try downgrading to isolate the problem.