Import an entire folder in Python - python

I've succeeding in importing a single file, but the file calls other files and I get an error. So I'm trying to import and entire folder. I would prefer not to import each file one by one since I know it must be possible to import the whole folder. Here is the syntax I used to import a file:
import importlib.machinery
import os
temp_directory2 = '/Users/me/PycharmProjects/inference_engine2/inference2/ancient/temp.py'
temp_directory = '/Users/me/PycharmProjects/inference_engine2/inference2/Proofs/main_loop.py'
main_directory = '/Users/me/PycharmProjects/inference_engine2/inference2/Proofs/'
b = os.path.exists(temp_directory)
loader = importlib.machinery.SourceFileLoader('temp', temp_directory)
handle = loader.load_module('temp')

You can add the path to the list sys.path at the beginning of your file, like so:
import sys; sys.path.insert(0, r'C:/Users/me/PycharmProjects/inference_engine2/inference2/Proofs')
Note since you are inserting the path at the beginning of the list, this is the first place python will go to look for a module.

Convert it to a package using __init__.py. more here : https://docs.python.org/2/tutorial/modules.html

Related

How to display a variable without a specific part?

So, i have a variable, for example dir = "Crypter.aes". I need to variable like dir, but without .aes. What gotta I do for that? I use directory parser, that make many dir with file name in that directory, and for each file I need to remove a certain part at the end - .aes
This is a task for the os.path module in the standard library.
import os.path
dir, _ = os.path.splitext("Crypter.aes")
If you're working a lot with file paths, you also might want to take a look at the pathlib module.
from pathlib import Path
dir = Path("Crypter.aes").stem

Convert import path to file path ('conf.settings' -> conf/settings.py)

I would like to convert the import path to file path.
I can check the OS and replace '.' with either '\' or '/' and suffix with '.py` sure - but I'm interested in a built in way.
importlib.util.find_spec('conf.settings').origin does not suit my needs because that imports the module and returns the entry from sys.modules, and I'm writing a static analysis tool that does not import the code, just parses it.
>>>from astroid.modutils import file_from_modpath
>>>file_from_modpath(['conf', 'settings'])
/tmp/project/conf/settings.py

Moving unsupported file extensions by python

I'm trying to move files from one directory to another using Python - spyder.
My file extension is *.OD which python does not support or read.
I have tried using the wildcard and leaving out the file extension (which does not work). Another file extension cannot be used for this particular file.
Moving python supported extensions such as .txt and .csv works fine.
import shutil
source = '//Original_Filepath/Extract*.od'
target = '//NewFilePath/Extract_*.od'
shutil.copy(source, target)
There are no errors, it just doesn't move/copy the file.
Thanks,
There are a couple of basic mistakes with how you're trying to copy the files. With shutil.copy you should not specify a glob, but instead the exact source and destination.
If instead you want to copy a set of files from one directory to another and (presuming the added underscore isn't a mistake) change the target, then you should try using pathlib in combination with shutil (and re if needed).
pathlib - Object-oriented filesystem paths
Try adapting this:
import pathlib
import shutil
import re
source = pathlib.Path('//Original_Filepath') # pathlib takes care of end slash
source_glob = 'Extract*.od'
target = pathlib.Path('//NewFilePath')
for filename in source.glob(source_glob):
# filename here is a Path object as well
glob_match = re.match(r'Extract(.*)\.od', filename.stem).group(1)
new_filename = "Extract_{}.od".format(glob_match)
shutil.copy(str(filename), str(target / new_filename)) # `/` will create new Path
If you're not interested in editing the target nor using any other advanced feature that pathlib provides then see Xukrao's comment.
Thank you all for your help. Much appreciated! :)
I was also able to copy the file with the below as well (a bit simpler).
I left out the * and used a date string instead.
import shutil
from datetime import datetime
now = datetime.now()
Org_from=os.path.abspath('//Original FilePath')
New_to=os.path.abspath('//New Path')
shutil.copy(os.path.join(org_from, 'File_' + now.strftime("%Y%m%d") + '.od'), os.path.join(New_to, 'File_' + now.strftime("%Y%m%d") + '.od'))
Cheers,
Jen

Failing to import a file

I am currently trying to code a searching program, which makes use of a program I've already written. It refuses to get to the second print statement.
print("Relevance: ")
# import sqlite3
import Breakdown.py as bd
import re, nltk
from nltk.corpus import wordnet
# from sqlite3 import Error
from autocorrect import spell
print("Input line: ")
The file structure looks like this:
However, I can't work out why it can't get past that import section.
This is somewhat important.
Thanks.
Just write:
import Breakdown as bd
python will import the Breakdown.py file as a module. It will be looking for any variable or function named "py" in the Breakdown module if you use:
import Breakdown.py as bd
... which I don't think is the case here.
You should put the Breakdown.py file in the path where you're starting Python or in one of the directories where Python looks for libraries:
import os
for p in sys.path:
print(p)
and use import Breakdown (no .py).
Or else add to sys.paththe folder where the module is with:
sys.path.append('/your/foldername')

How to import using a path that is a variable in Python

I am trying to make a program that will go through and visit an array of directories and run a program and create a file inside.
I have everything working except that I need to figure out a way to import from a new path each time to get to a new directory.
For example:
L =["directory1", "directory2", "directory3"]
for i in range(len(L)):
#I know this is wrong, but just to give an idea
myPath = "parent."+L[i]
from myPath import file
#make file... etc.
Obviously when I use myPath as a variable for the path to import, I get an error. I have tried several different ways by searching online through Stack Overflow and reading OS and Sys documentation, but have come to no working result.
You can use 'imp' module to load source code of python scrips
import imp
root_dir = '/root/'
dirs =["directory1", "directory2", "directory3"]
for _dir in dirs:
module_path = os.path.join(root_dir,_dir,'module.py')
mod = imp.load_source("module_name", module_path)
# now you can call function in regular way, like mod.some_func()
I want to create a text file inside each directory. To do this I must
cycle through my array and take each directory name so I can visit it.
import is for loading external modules, not creating new files, if creating new files is what you want to do, use the open statement, and open the not yet existing file with 'w' mode. Note: the directory must exist.
from os.path import join
L =["directory1", "directory2", "directory3"]
for d in L: # loop through the directories
with open(join(d,"filename.txt"), "w") as file:
pass # or do stuff with the newly created file

Categories

Resources