Home > OS >  import file as module in Python
import file as module in Python

Time:06-30

I wanted to make a cmd tool. I created two files, one named main.py, and the other named version.py there are in the same directory

version.py:

import os

def pyVersion():
    os.system("python --version")

main.py:

import version

version.pyVersion()

I think it should work, but when I run main.py, it prints:


  File "C:\Users\User\PycharmProjects\cmd tool\main.py", line 1, in <module>
    import version
ModuleNotFoundError: No module named 'version'

CodePudding user response:

Normally Python should use folder C:\Users\User\PycharmProjects\cmd tool\ to search imported modules and you may have this folder even on list sys.path

But if it doesn't have this folder on list then you may add it manually before importing module.

import sys

# add at the end of list
#sys.path.append(r'C:\Users\User\PycharmProjects\cmd tool\')

# add at the beginning of list
sys.path.insert(0, r'C:\Users\User\PycharmProjects\cmd tool\')

import version

# ... code ...

To make it more universal you can use os to get this folder without hardcoding

import os

BASE = os.path.dirname(os.path.abspath(__file__))
print('BASE:', BASE)

import sys

sys.path.insert(0, BASE)

import version

# ... code ...

CodePudding user response:

  1. Just import file without the .py extension.
  2. A folder can be marked as a package, by adding an empty __init__.py file.
  3. You can use the __import__ function, which takes the module name (without extension) as a string extension.

CodePudding user response:

change please the class name , and make the first letters uppercase

Version.py
def pyVersion():
    os.system("python --version")
Main.py
import Version

Version.pyVersion() 

and the code must work and he will give you a result Python version

  • Related