Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python import fails in windows, but not linux

When I import a module, it works on linux, but fails in windows, with the error:

<Directory>\src>main.py
Traceback (most recent call last):
  File "<Directory>\src\main.py", line 12, in <module>
    from parser.parser import Parser
ImportError: No module named parser

On windows it seems that it cannot find the file parser.py (created by me). I don't understand why because it found all the other modules.

[folder:
   - main.py
   - parser/__init__.py
   - parser/parser.py]
like image 774
Frenkyk Avatar asked Jun 27 '26 18:06

Frenkyk


2 Answers

The problem is with the package name parser . By importing from parser you import the parser module from the standard library that has no parser.parser submodule. See parser.

like image 59
Chintan Avatar answered Jun 29 '26 07:06

Chintan


I encountered the same problem, and got it solved.

Here's how.

Check your sys.path (import it first) to see whether your coding-file's directory is included in it. If not, append it.

That's my code:

import sys
import os
sys.path[0]=os.path.dirname(os.path.realpath(__file__))

Tell me if it doesn't work.

BTW, I'm Chinese so ignore any grammatical errors. I think you understand what I mean.

like image 34
Gerald Avatar answered Jun 29 '26 07:06

Gerald



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!