【问题标题】:Is it possible for a python file to write another python file? [closed]python文件是否可以编写另一个python文件? [关闭]
【发布时间】:2020-04-19 07:37:41
【问题描述】:

我正在为 python 创建一个工作表生成器。我可以让 python 创建另一个 .py 文件并写入它吗?

class ws:

    def _init_(self, number, ctype):
        self.number=wsno
        self.ctype=plang
        x=input('Questions file:')
        y=open(x, mode='r')
        z=f.read()
        a,b,c,d,e=z.split(';')
        wsno=input('Worksheet number: ')
        wspl=input('Language: ')
        title=wspl+" Worksheet "+wsno
        q1="1: "+ws.a
        q2="2: "+ws.b
        q3="3: "+ws.c
        q4="4: "+ws.d
        q5="5: "+ws.e

def renderws():

renderws() 是我想让 python 文件生成另一个 python 文件的地方。提前致谢!

【问题讨论】:

  • 如果只想执行,不需要保存,直接使用exec()即可。否则,只需打开文件并写入即可。
  • open('somefile.py', 'w')? Python 几乎可以写入您要求的任何类型的文件,所以是的,您可以写入 python 文件
  • Python 源文件只是一个文本文件;但是自生成代码通常是一种反模式。可能想要在另一个脚本中执行代码的脚本无论如何都可以轻松地执行该代码。
  • 可疑问题。
  • 错字:_init_ -> __init__

标签: python code-generation


【解决方案1】:

这绝对有效:

>>> import os
>>> with open( 'test.py', 'w' ) as fout :
...     fout.write( 'print "hello, python"' )
... 
>>> os.system( 'python test.py' )
hello, python
0
>>> 

【讨论】:

    猜你喜欢
    • 2020-03-14
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多