topcan5
topcan5

Reputation: 1707

Python function return the content a .py file

I have some python files, .py, each has several dictionaries to store some constant data. The data here will never change. I use dictionary in .py file, so I can import them later easily. Example of a file:

car = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
driver = {
  "name": "Elon",
  "age": 51
}

I want to write a function to take a param and return the content of the corresponding .py file. What's the best way to do it? Do I just convert the .py file to bytes in the function and convert it back to .py file in the outside?

Upvotes: 2

Views: 177

Answers (3)

Yaakov Bressler
Yaakov Bressler

Reputation: 12018

Let's assume your project has the following structure:

my_project
|-- __init__.py
|-- data.py
|-- main.py

The usual way to do this is to import the variables from the file (submodule). Your main.py should look like this:

from data import car

def my_function():
    print(car)

Upvotes: 0

OneCricketeer
OneCricketeer

Reputation: 191728

Assuming those are in data.py

Then write another script to import those variables

from data import car, driver

print(car, driver)

Upvotes: 1

Matteo
Matteo

Reputation: 91

It seems that what you need is JSON files. It is a format to store structured data in key/value style like but in files, while dictionaries are data structures stored in main memory.

Python offers simple function to handle JSON and make conversion to and from dictionaries.

import json

insert this in your code and take a look to official python docs here https://docs.python.org/3/library/json.html

Upvotes: 1

Related Questions