Bringing in a function from a library in Python 2.7

I need assistance with importing the foo function from the mod.py file.

In an attempt to resolve this, I have created a new empty file called init.py within the directory C/Users/me/Desktop/NF. I also tried using __init__.py

My understanding was that having an empty init file in the NF directory would allow for the successful import. Can you please guide me on how to rectify this issue?

from C.Users.me.Desktop.NF.mod import foo

Traceback (most recent call last):
   File "<pyshell#3>", line 1, in <module>
   from C.Users.me.Desktop.NF.mod import foo
ImportError: No module named C.Users.me.Desktop.NF.mod

Answer №1

Ensure The Directory is Added to the PYTHONPATH Environment Variable.

  1. Set up a user variable PYTHONPATH=%PYTHONPATH%;C/Users/me/Desktop/NF;
  2. Make sure you include __init__.py in the directory to designate it as a python package.
  3. Now, you can easily import modules using a simple python import statement.

import mod from mod import foo

Answer №2

To properly set up your PYTHONPATH environment variable, follow the recommendations provided in earlier responses. Once you have done so, you can easily access the library from your directory in the Python prompt by entering the following commands:

>>import sys
>>print(sys.path)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

My goal is to have my program generate a file that stores user input without duplicating it. (Python)

Here is the code I am currently using: i=0 f= open("username list.txt", "a+") for i in range(i+1): user=input("Enter your Pokémon Go username to continue.") if user != i: f.write(user) print("Welcome,", user) f.close() However, when ...

Obtain the index for a data point using a SciPy sparse array

Currently, I am working on a CSR sparse array where there are many empty elements or cells. This array needs to support both forward and backward indexing. In other words, I should be able to provide two indices and receive the corresponding element (e.g., ...

Who snatched the python requests shib_idp_session cookies from the cookie jar's grasp?

Currently, I am experimenting with leveraging Python (3.9.1) along with requests (2.25.1) to log in using Shibboleth and Duo two-factor authentication (2FA). I possess all the necessary credentials for this process and regularly perform manual logins throu ...

How can I remove an empty row from a list of dictionaries using a for loop in Python?

I need assistance with a Python code snippet that involves manipulating dictionaries in a list. Specifically, I have a list of dictionaries named "rows" where some dictionaries contain empty values indicated as "None." How can I create a for loop to iterat ...

Tips for retrieving the xpath of elements within a div using python selenium

<div class="col-md-6 profile-card_col"> <span class="label">Company Name :</span> <p class="value">Aspad Foolad Asia</p> </div> For a while now, I've been trying to troublesho ...

How to export multiple Excel files from a pandas dataframe by sorting based on column values and keeping the formatting intact?

I need to split a dataframe into individual files based on unique strings in the "names" column. I have figured out how to do this with a simple function: f = lambda x: x.to_excel(os.getcwd() + '\\{}.xlsx'.format(x.name), index=False) d ...

Python implementation of the Velocity-Verlet algorithm for a double-well potential

Currently, I am working on implementing the Verlet algorithm to model a double well potential V(x) = x^4-20x^2 in order to create a basic phase portrait. However, the resulting phase portrait has an irregular oval shape and appears to be incorrect. I suspe ...

Develop a script that filters the load information and stock market data contained in target.csv for specific subsets

Create a program that extracts specific data subsets from the target.csv file related to stock market information. Load the contents of target.csv into a variable named 'target'. From the 'target' data, create a new dataframe called &ap ...

The attempted decoding of a JSON object was unsuccessful. The provided JSON is not valid

I've encountered an unusual issue In my program, I am sending a JSON string through a socket: json_string = JSONEncoder().encode({ "id_movil": str(id_movil), "correo": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfema ...

What is the best way to avoid the "/" character when using send_keys?

When running a script that writes code into a textarea on a website, I encountered an issue. The first four lines were being written correctly until var url = "https:, at which point the cursor would jump to the upper left of the text area before continuin ...

Python is a powerful language that can be used to capture and analyze

I am using a WebDriver through Selenium to automate opening a browser, directing it to an IP address, performing various tasks, and then closing it. My goal is to track all URLs accessed during this process. This includes any ads that are displayed, CSS c ...

Python code: Transforming points on a contour into a bounding box

Currently, I am analyzing medical images using XML files that contain contour coordinates detailing regions of interest. Despite successfully extracting these points, I am facing challenges in converting them into a bounding box suitable for creating masks ...

The error message in Phyton states that only integers (or booleans) can be used as indices, but I specifically require floats for this operation

Encountering a persistent issue where I am unable to use dtype=np.int8 due to the requirement of precise floats for all arrays. Currently engaged in developing a simple model focusing on the spread of covid-19 infection. Experimenting with multiple numpy a ...

Encountering an ElementClickInterceptedException while trying to click the button on the following website: https://health.usnews.com/doctors

I am currently in the process of extracting href data from doctors' profiles on the website . To achieve this, my code employs Selenium to create a web server that accesses the website and retrieves the URLs, handling the heavy lifting for web scrapin ...

How can you identify the widget using its ID when you have assigned it a value of -1 in wxPython?

Today, I am working on some wxPython code and found this snippet (I removed the irrelevant parts): def CreateRowOne(self, pan): hbox1 = wx.BoxSizer(wx.HORIZONTAL) hbox1.Add(wx.Button(pan, -1, "250 Words"), 1, wx.EXPAND | wx ...

How can you retrieve all the values associated with a "base" key within a nested dictionary?

I have been searching for a solution to my problem but have not been able to find one. If you know of any, please guide me in the right direction! Here is the dictionary in question: https://i.stack.imgur.com/w9F7T.png The data is loaded using json.load ...

In lxml, HTML elements may be encoded incorrectly, such as displaying as &#x41D;&#x430;&#x439; instead

Having trouble printing the RSS link from a webpage because it's being decoded incorrectly. Check out the snippet of code below: import urllib2 from lxml import html, etree import chardet data = urllib2.urlopen('http://facts-and-joy.ru/') ...

Python script to extract data from a JSON file

Struggling to read data from a JSON file and display the values? Having trouble figuring out how to access all the values from the first dictionary in the list? Here's what you want to print: website: https://www.amazon.com/Apple-iPhone-GSM-Unlocke ...

Disregard the patch decorator at the class level for a specific test

I am currently dealing with a class in a module structured like this: class Foo: def bar1(self) -> str: return "bar1" def bar2(self) -> str: bar = bar1() return bar def bar3(self) -> str: bar ...

Obtain the name of the month from the given date input

Hey there! I've been working on a function that allows users to input their birthdate and receive relevant information, like the month name corresponding to the date they entered. However, I'm currently only getting the month number instead of th ...