使用Python的基本I / O来操纵或创建Python文件? [英] Using Python's basic I/O to manipulate or create Python Files?

查看:117
本文介绍了使用Python的基本I / O来操纵或创建Python文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最有效的方法-我知道这不是很有效,但是老实说我找不到更好的方法来操作Python(.py)文件,添加/减去/附加代码,使用

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 the basic file I/O module included in Python?

例如:

obj = open('Codemanipulationtest.py', 'w+')
obj.write("print 'This shows you can do basic I/O?'")
obj.close()

将操纵我拥有的名为 codemanipulationtest.py的文件,并向其添加打印语句。这是可以解决的问题,还是有任何更简单或更安全/有效的方法来操作/创建新的python代码?

Will manipulate a file I have, named "codemanipulationtest.py", and add to it a print statement. Is this something that can be worked upon or are there any easier or more safe/efficient methods for manipulating/creating new python code?

我已经阅读了以下内容:< a href = https://stackoverflow.com/questions/768634/python-parse-a-py-file-read-the-ast-modify-it-then-write-back-the-modified>解析a。 py文件,读取AST,对其进行修改,然后写回修改后的源代码

I've read over this: Parse a .py file, read the AST, modify it, then write back the modified source code

说实话,I / O方法似乎更容易。我是Python的新手,所以我可能只是在表现愚蠢.....感谢任何响应。

And honestly it seems like the I/O method is easier. I am kind of newbish to Python so I may just be acting stupid.....thanks in advance for any responses.

编辑

这一切的重点仅仅是玩转效果和代码一起玩。我当时想把我最终使用的任何东西都连接到某种学习算法上,看看它一次生成少量代码的效果如何,然后看看它可以从那里去哪里。。

The point of it all was simply to play around with the effects playing around with the code. I was thinking of hooking up whatever I end up using to some sort of learning algorithm and seeing how well it could generate little bits of code at a time, and seeing where it could go from there....

推荐答案

要继续生成代码,我会将其分解为各种类,IF类,FOR类,等等。然后,您可以使用输出,其中每个类都有一个to_str()方法,您可以依次调用该方法。

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.

这篇关于使用Python的基本I / O来操纵或创建Python文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆