Import text file as a module in Python

Viewed 2915

I want to import a plain text file, no matter the extension cause I want to use my own, as a module in python.

For example. I have the strings for my program in separated .py files, and, depending on what language is selected, I import one file or the other.

Everything works well with this, but, I want to make this file, apparently not readable for a common user, so, I want to give them a custom extension that any of the programs installed can't read. But, due that import only work with .py files, I want to know if there is a way to do this with other file types. Or if is it another way to do something like this.

Thank you.

1 Answers

maybe read file sources and use eval method?

You may use it as

def import_module(filename):
    with open(filename, 'r') as file:
        file_contents = file.read()
    module_object =  exec(file_contents)
    return module_object

But that variant are not secure!

And such question was in stackoverflow read it

Related