Skip to content Skip to sidebar Skip to footer

Using Python's Basic I/o To Manipulate Or Create Python Files?

Would the most efficient way-and I know it's not very efficient, but I honestly can't find any better way-to manipulate a Python (.py) file, to add/subtract/append code, be to use

Solution 1:

To go about with generating the code I would break it out into various classes, IF class, FOR class, and so on. Then you can use the output wherein each class has a to_str() method that you can call in turn.

statements = [ ... ]

obj = open( "some.py", "w+" )

for s in statements:
    obj.write( s.to_str() )

obj.close()

This way you can extend your project easily and it will be more understandable and flexible. And, it keeps with the use of the simple write method that you wanted.

Depending on the learning algorithm this break out of the various classes can lead quite well into a sort of pseudo genetic algorithm for code. You can encode the genome as a sequence of statements and then you just have to find a way to go about passing parameters to each statement if they are required and such.

Solution 2:

It depends on what you'll be doing with the code you're generating. You have a few options, each more advanced than the last.

  • Create a file and import it
  • Create a string and exec it
  • Write code to create classes (or modules) on the fly directly rather than as text, inserting whatever functions you need into them
  • Generate Python bytecode directly and execute that!

If you are writing code that will be used and modified by other programmers, then the first approach is probably best. Otherwise I recommend the third for most use cases. The last is only to masochists and former assembly language programmers.

If you want to modify existing Python source code, you can sometimes get away with doing simple modifications with basic search-and-replace, especially if you know something about the source file you're working with, but a better approach is the ast module. This gives you an abstract representation of the Python source that you can modify and then compile directly into Python objects.

Post a Comment for "Using Python's Basic I/o To Manipulate Or Create Python Files?"