Read .txt file like .py file

K

King

I have a text file and contents are:

Help="""
Code is written by xteam.
"""
value = 0.0


How do I read this file like python syntax. What I mean is first
readline operation should return complete declaration of 'Help'
variable. If I evaluate this string then it should create a 'Help'
variable with it's value.

May be something related to 'parsing' would help but I don't know much.
 
S

Stefan Behnel

King said:
I have a text file and contents are:

Help="""
Code is written by xteam.
"""
value = 0.0


How do I read this file like python syntax. What I mean is first
readline operation should return complete declaration of 'Help'
variable. If I evaluate this string then it should create a 'Help'
variable with it's value.

If you trust the author of the file and you're sure the code in the text file
isn't an Internet worm and won't delete all your files, you can get away with
the built-in "execfile" function.

If you want more security, look at the compiler module and the ast module.
They allow you to parse the file like a normal Python source file, and IIRC,
there are also ways to execute single statements from a syntax tree.

Stefan
 
K

King

Well, I have a look to into compiler module and gave it a try using
compiler.parseFile and compiler.walk but I haven't got what I need
here.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top