Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I import a Python library located in the current working directory? [duplicate]

I'm writing an installation program that will pull a script out of an existing Python file and then use it in the main Python program. What I need to know how to do is import <file> from the current working directory, not the standard library or the directory the main code is in. How can I do that?

like image 566
Nathan2055 Avatar asked Apr 15 '13 17:04

Nathan2055


People also ask

How do I import a file from one directory to another in Python?

We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.

How do I import a Python location?

append() Function. This is the easiest way to import a Python module by adding the module path to the path variable. The path variable contains the directories Python interpreter looks in for finding modules that were imported in the source files.

How can you retrieve the current working directory in Python?

To find the current working directory in Python, use os. getcwd() , and to change the current working directory, use os. chdir(path) .

What is the Python command for printing the current working directory?

getcwd() os. getcwd() returns the absolute path of the current working directory where Python is running as a string str . getcwd stands for "get current working directory", and the Unix command pwd stands for "print working directory".


1 Answers

This works:

import os
import sys
sys.path.append(os.getcwd())
import foo
like image 102
Tyler Eaves Avatar answered Oct 11 '22 18:10

Tyler Eaves