0

How can I import different .py files in python based on user-input?

def main():
    FileName = input(">")
    file = FileName.replace(".py", "")
    import file
    print(test) #from the file imported

main()

Something like this, so I can import a certain file created with the name of the user input, and that file imported contains a string or a list and so I could print that string or list within the main python file.

Ryaagard
  • 13
  • 2
  • Be aware that this could well count as a security vulnerability if you don't take steps to limit which files on the filesystem can be imported. Importing a python program runs it, so importing a malicious file could be dangerous. – match Jan 13 '20 at 22:23

1 Answers1

1

You can use import_module from importlib

from importlib import import_module

file = import_module(FileName.replace(".py", ""))
print(file.test)
zamir
  • 2,144
  • 1
  • 11
  • 23