2

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 Answers1

1

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

Crazy
  • 324
  • 2
  • 8
  • Ok, this works as expected, but, why this isn't secure? – David González Blazman Jan 14 '19 at 12:24
  • 1
    Because, maybe that file will be replaced with file with some code for getting remote access to computer wich execute your program – Crazy Jan 14 '19 at 12:28
  • 1
    as another variant (such insecure), you may compile your code into some variable in code, and write it as pickled file in working directory – Crazy Jan 14 '19 at 12:30
  • @DavidGonzálezBlazman, make my answer as right if it helps your – Crazy Jan 14 '19 at 12:34
  • Ok, I have this file encoded and with control words to make sure this is the correct file so I can use exec properly secured. Thanks! – David González Blazman Jan 14 '19 at 12:53
  • Note: This answer doesn't work, in-so-far as it's not equivalent to `import` or `importlib.import_module` since it doesn't import any of the imports present within the module... :/ – George Jul 01 '21 at 21:58