简体   繁体   中英

read a variable from a python file

When I searched for this problem, I mostly saw how to import from a txt file or other file format. Not from a python file.

I need to write a function ( get_seeds() ) that takes in a path in string and extract a variable from that.py file. That.py file supposedly only has one variable named seeds .

Given:

path =./data/M060812_Yac128/seeds.py

seeds = {
    "HLS1": {'X': 44, 'Y': 52},
    'HLS2A': {'X': 108, 'Y': 66},
    'HLS2B': {'X': 91, 'Y': 85},
    'FLS1': {'X': 56, 'Y': 39},
    'FLS2': {'X': 104, 'Y': 61},
    'BCC2': {'X': 68, 'Y': 69},
    'BCC2S2': {'X': 92, 'Y': 72},
    'mBC': {'X': 34, 'Y': 30}
}

get_seeds.py:

def get_seeds(path):
    Path = os.path.normpaath(path)
    from Path import seeds
    return seeds

This obviously doesn't work... because I assume from...import... needs to be outside of the function.

Try using importlib.import_module instead to import where the name of the module is a string. Additionally, use sys.path to include the path of the folder where the script resides so that you can import it by name and use it in your script

import os
import importlib

def get_seeds(path):
    Path = os.path.normpath(path)
    folders = Path.split('/') # create list of each folder component of the path
    folder_path = '/'.join(folders[:-1]) # remove the file from the path to specify path to the folder containing script
    sys.path.insert(1, folder_path) # add folder path to sys path so python can find module

    mod = importlib.import_module(folders[-1][:-3]) # get rid of .py extension and use only name of the script rather than entire path
    return mod.seeds

This will work if your file is static and not generated. If you need to be able to access multiple files that could have any name, there is another answer here that will work better.

if you put an __init__.py file (just a blank file with that name) in./data/ and./data/M060812_Yac128/ you can from data.M060812_Yac128.seeds import seeds then call the function.

This makes the subfolders python modules

Directory structure:

在此处输入图像描述

seeds.py:

seeds = {
    "HLS1": {'X': 44, 'Y': 52},
    'HLS2A': {'X': 108, 'Y': 66},
    'HLS2B': {'X': 91, 'Y': 85},
    'FLS1': {'X': 56, 'Y': 39},
    'FLS2': {'X': 104, 'Y': 61},
    'BCC2': {'X': 68, 'Y': 69},
    'BCC2S2': {'X': 92, 'Y': 72},
    'mBC': {'X': 34, 'Y': 30}
}

Main python file:

from data.M060812_Yac128.seeds import seeds

print(seeds)

Output:

{'HLS1': {'X': 44, 'Y': 52}, 'HLS2A': {'X': 108, 'Y': 66}, 'HLS2B': {'X': 91, 'Y': 85}, 'FLS1': {'X': 56, 'Y': 39}, 'FLS2': {'X': 104, 'Y': 61}, 'BCC2': {'X': 68, 'Y': 69}, 'BCC2S2': {'X': 92, 'Y': 72}, 'mBC': {'X': 34, 'Y': 30}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM