Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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?

1 Answer

0 votes
by (106k points)

You can use the below-mentioned code to import a specific Python file at 'runtime' with a known name:

import os 

import sys

scriptpath = "../Test/MyModule.py" 

sys.path.append(os.path.abspath(scriptpath)) 

import MyModule

Related questions

0 votes
1 answer
asked Jun 26, 2019 in Python by Anurag (33.1k points)
0 votes
1 answer
asked Jul 13, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
asked Sep 25, 2019 in Python by Sammy (47.6k points)

Browse Categories

...