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
Related
I have two files /somewhere/main.py and /somewhere/repeated_name.py and then I have other file /random/path/repeated_name.py. How do I import a function from /random/path/repeated_name.py into /somewhere/main.py?
I think you can use shutil for that. All you need is the absolute path and then use the shutil.move(src, dst) method. And then you just have to use the from file import method without bothering about the folder.
But if you want to import a function to another file, I think this article should answer your question: https://www.geeksforgeeks.org/python-import-module-from-different-directory/
You can use:
from somewhere.repeated_name import func_name
Just make sure folder also contains an init.py, this allows it to be included as a package.
I'm working on the pythonizer, a program to translate perl to python, and I'm looking to translate the statement "require FILENAME;" to python. In this case I need to generate "from FILENAME import *". I figured out the "from FILENAME" part (here BASENAME is the FILENAME without the path or extension):
from importlib.machinery import SourceFileLoader
module = SourceFileLoader(BASENAME, FILENAME).load_module()
and the import * part is coded as:
__import__(name, fromlist=['*'])
but how do I combine them?
I see _handle_fromlist in importlib._bootstrap, but calling an internal routine is most likely not the right answer here.
Here is my second thought about implementing this:
[_p, _m] = _prep_import(FILENAME)
sys.path.insert(0, _p)
__import__(_m, fromlist=['*'])
sys.path.pop(0)
def _prep_import(filepath):
"""Prepare a filepath for import by getting the abspath, splitting
it from the filename, and removing any extension. Returns a tuple of
the path and the filename"""
return os.path.split(os.path.splitext(os.path.abspath(filepath))[0])
Where _prep_import() looks at the FILENAME (which may be an expression), removes any extension, grabs any path info from it into the first result, and leaves the basename as the second result. Note that the FILENAME may contain dashes (-), and I believe __import__ is OK with that.
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
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
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