Zain Raza
Zain Raza

Reputation: 13

How to use a python program stored in a text file?

I'm making a troubleshooting program in which I need to take a python program which is stored in a text file, but I can't use the 'import' module. To clarify this, there would be a python program stored as a '.txt' file, and in the main program I would take this text file and be able to use it as a subprogram. I've tried doing this, but I have had no clue of how to go about it, especially since I do not have much experience of Python. Below is roughly the program. I don't know how to format it either, but here goes:

phonechoice = input("What type of phone do you have?")

if 'iphone' in phonechoice:
    #here I would load a text file which contains the program for the iphone
    #which asks them what problem they have with their phone and gives a solution

I'm wondering how I can do this. I thought how I could do this and maybe I could 'copy and paste' the program, line by line, into a definition, which I could then use. Would this work, and if it doesn't then in what other way could I do it?

Upvotes: 1

Views: 231

Answers (2)

wim
wim

Reputation: 362517

Rename the text file to a python file, i.e. change the extension to ".py". This does not change the fact that it is a text file, just like renaming a picture.jpg file to picture.txt does not change the fact that it's an image file.

If you have some wacky requirement to import a module saved in file with a .txt extension, you can not use an import statement. But it is still possible to import like this:

import imp
my_module = imp.load_source('my_module', 'example.txt')

Upvotes: 3

Mark Skelton
Mark Skelton

Reputation: 3891

I am a bit reluctant to answer a "homework" type question, but I will give you some pointers on what you need to do. If I have a text file with this in it:

def main():
    print("Hello")

main()

I could execute the code with the exec function like this:

with open("filename.txt") as file:  #filename should be the name of the file
    data = file.read()

exec(data)  #this executes the code

The output would be as expected:

Hello

Hopefully this will shed some light on your problem!

Upvotes: -1

Related Questions