Read .txt file like .py file

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • King

    Read .txt file like .py file

    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.
  • Stefan Behnel

    #2
    Re: Read .txt file like .py file

    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

    Comment

    • King

      #3
      Re: Read .txt file like .py file

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



      Comment

      Working...