I tried the answers in this question to no avail so I thought it'd be worth a separate question. The directory layout is as follows:
aale/
2/
2.py
__init__.py
3/
3.py
__init__.py
__init__.py
The names are unfortunately unable to change (this is the layout given to us for a HW problem). I am trying to import 2 from 3 but it doesn't seem to be working. I tried using importlib as:
two = importlib.import_module('2.2') as well as
two = importlib.import_module('2')
which didn't work also (gave a ModuleNotFoundError: No module named '2' error). Any help / other methods would be appreciated. I am using Python 3.6.
Assuming your script is in the aale directory, you will need to do your import like:
two = importlib.import_module('aale.2.2')
You can use __import__, i.e.:
two = __import__("2.2") # or __import__("aale.2.2")
three = __import__("3.3") # or __import__("aale.3.3")
Equivalent to:
import 2.2 as two
import 3.3 as three
which isn't possible.
Notes:
According to PEP 8 styling guide:
Package and Module Names should have short, all-lowercase names. Underscores can be used in the module name
if it improves
readability.
I've tested the imports using the same folder structure as in your
question and no errors were shown.
References:
https://stackoverflow.com/a/16644280/797495
In python, how to import filename starts with a number
PEP 8 -- Style Guide for Python Code
You can use pathlib
It is basic:
from pathlib import Path
BASE_LOCATION = Path(__file__).parent
(You can add .parent to get to the folder above and so on.)
Edit
If this doesn't help you, you can try import weirdimport.
You can read more about this here.
Hope this helps!
Related
I'm really unexpert in python, so forgive my question if stupid.
I'm trying a simple script that operates on all the files in a folder.
However, I apparently can only access the folder recursively!
I explain. I have a folder, DATA, with subfolders for each day (of the form YYYY-MM-DD).
If I try
for filename in glob.glob('C:\Users\My username\Documents\DATA\2021-01-20\*'):
print filename
I get no output.
However, if I try instead
for filename in glob.glob('C:\Users\My username\Documents\DATA\*\*'):
print filename
the output is that expected:
C:\Users\My username\Documents\DATA\2021-01-20\210120_HOPG_sputteredTip0001.sxm
C:\Users\My username\Documents\DATA\2021-01-20\210120_HOPG_sputteredTip0002.sxm
...
I even tried different folder names (removing the dashes, using letters in the beginning, using only letters, using a shorter folder name) but the result is still the same.
What am I missing?
(BTW: I am on python 2.7, and it's because the program I need for the data is only compatible with python 2)
Beware when using backslashes in strings. In Python this means escaping characters. Try prepending your string with r like so:
for filename in glob.glob(r'C:\Users\My username\Documents\DATA\*'):
# Do you business
Edit:
As #poomerang has pointed out a shorter answer has previously been provided as to what 'r' does in Python here
Official docs for Python string-literals: Python 2.7 and for Python 3.8.
Recursive file search is not possible with glob in Python 2.7. I.e. searching for files in a folder, its subfolders, sub-subfolders and so on.
You have two options:
use os.walk (you might need to change your code's structure however)
Use the backported pathlib2 module from PyPI https://pypi.org/project/pathlib2/ - which should include a glob function supporting the recursive search using ** wildcard.
This question already has answers here:
How do I import other Python files?
(23 answers)
Closed 2 years ago.
I have a folder of this file structure:
Desktop
tech_comp
googledash.csv
viz.py
sql_load.py
company_AL
__init__.py
functionloads.py
decisionplans.py
niches.py
actions.py
I am working with VScode in the following path as described above: C:\Users\username\Desktop\tech_comp\company_AL
I have written a bunch of list in the decisionplans.py now I am trying to load it in the actions.py I am working with. Here is what I did.
from company_AL import decisionplans
It does not show errors in the compiler but when I run I get the following.
ModuleNotFoundError: No module named 'company_AL'
I do not intend to publish it as online as this is a private project, please how do I handle this?
Thanks in advance
You have many solutions to solve your problem :
1. Add compagn_AL folder to your PYTHON_PATH
It depends of your OS but there is tutorials that explians better than me
2. Change the PATH for your script
import sys
sys.path.append('../') # or "C:\Users\username\Desktop\tech_comp\"
and then
from compagny_AL import decisionplans
3. Import it directly (not recommended)
You can just
import decisinplans
I think you just need to do import decisionplans or from .company_AL import decisionplans because you are already in the company_AL.
I am using the cx_Freeze script located in the Python36/Scripts folder on a regular basis to convert python files into executables and it works fine. However it seems to still not being able to convert numpy so I am trying to make it work by adding an option into the main.py which is used by the cx_Freeze script described above. This main.py is located in the site-packages/cx_Freeze folder.
Thomas K. provided a solution here: Creating cx_Freeze exe with Numpy for Python
by adding this line to the options:
options = {"build_exe": {"packages": ["numpy.lib.format"]}}
Is it possible to add this line to the main.py in the options section? If so how would I do that?
Your help is much appreciated.
If I understand correctly what you like to do, you could try to add the following two lines to the file site-packages/cx_Freeze/freezer.py
## -127,6 +127,8 ## class Freezer(object):
self.includes = list(includes)
self.excludes = list(excludes)
self.packages = list(packages)
+ if 'numpy.lib.format' not in self.packages:
+ self.packages.append('numpy.lib.format')
self.namespacePackages = list(namespacePackages)
self.replacePaths = list(replacePaths)
self.compress = compress
Can a python script located in D:\Folder_A\Folder_B\be used to change variables in another python script located in D:\Folder_A\Folder_C\, and then print them out on the console?
NOTE: I'm a beginner in Python, and I'm using v2.7.8.
EDIT: To answer #Rik Verbeek, I created a python file in location A (D:\Folder_A\Folder_B\), and another file at location B (D:\Folder_A\Folder_C\), with both the folders (Folder_B & Folder_C) located in D:\Folder_A\. In the 2nd .py file, I wrote the following:
a = 0
b = 0
Now I want to change these variables from the 1st .py file to 5 and 10 respectively, and print them to the console. Also, these files are not in the Python libraries, but are instead, located in another folder(Folder_A).
To answer #Kasra (and maybe #cdarke), I don't want to import a module, unless it is the only way.
If you have some "global" variables I think is a good idea to have them in a separated module and import that module from each place you need them. This way you only have to do it as cdarke has commented.
I use python to write scripts for Autodesk Maya. Maya is a cross-platform software and internally use forward slash. If I use os.path.join operation on windows it can result paths like this:
e:/Test\\TemplatePicture.jpg
My idea is that as long as I don't use ms-dos commands easier way to join path parts like this:
pathPart1 = "e:"
pathPart2 = "Test"
pathPart3 = "TemplatePicture.jpg"
path = "s%/s%/s%" % (pathPart1, pathPart2, pathPart3)
Is there something that makes it a bad idea?
When you import os, python will create an os.path specific to your platform. On linux its posixpath and on windows its ntpath. When you are working on Maya paths, use posixpath. It will follow linux conventions even on windows. When you need to go native, convert using the realpath for your current system.
import os
import posixpath
maya_path = posixpath.join('a','b','c')
local_path = os.path.realpath(maya_path)
I don't see any problems with this.
In fact there is a related question here.
To summarize the discussion within the provided link - you either let python handle file paths or you do it all yourself