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?
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.
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.
To find the current working directory in Python, use os. getcwd() , and to change the current working directory, use os. chdir(path) .
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".
This works:
import os
import sys
sys.path.append(os.getcwd())
import foo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With