Read .txt file like .py file

Stefan Behnel stefan_ml at behnel.de
Sun Jul 27 15:28:15 CEST 2008


King wrote:
> 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



More information about the Python-list mailing list