Skip to content
Fix Code Error

How to import other Python files?

March 13, 2021 by Code Error
Posted By: Anonymous

How do I import other files in Python?

  1. How exactly can I import a specific python file like import file.py?
  2. How can I import a folder instead of a specific file?
  3. I want to load a Python file dynamically at runtime, based on user
    input.
  4. I want to know how to load just one specific part from the file.

For example, in main.py I have:

from extra import * 

Although this gives me all the definitions in extra.py, when maybe all I want is a single definition:

def gap():
    print
    print

What do I add to the import statement to just get gap from extra.py?

Solution

importlib was added to Python 3 to programmatically import a module.

import importlib

moduleName = input('Enter module name:')
importlib.import_module(moduleName)

The .py extension should be removed from moduleName. The function also defines a package argument for relative imports.

In python 2.x:

  • Just import file without the .py extension
  • A folder can be marked as a package, by adding an empty __init__.py file
  • You can use the __import__ function, which takes the module name (without extension) as a string extension
pmName = input('Enter module name:')
pm = __import__(pmName)
print(dir(pm))

Type help(__import__) for more details.

Answered By: Anonymous

Related Articles

  • Is CSS Turing complete?
  • [Vue warn]: Error in render: "TypeError: Converting circular…
  • react-table has a issue with rendering in next.js
  • Aurelia UX showcase app fails to load
  • Centering in CSS Grid
  • Uncaught TypeError: c.querySelectorAll is not a function
  • How to change the color of vaadin-select-text-field in the…
  • Mobile browsers add a gap at the end of final element via…
  • Python is not calling fucntions properly
  • How not to get a repeated attribute of an object?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Remove all whitespace in a string

Next Post:

How can I get the source directory of a Bash script from within the script itself?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error