Whats the best way to write python code into a python file?

后端 未结 4 1031
独厮守ぢ
独厮守ぢ 2021-02-07 10:47

I want to write a script (generate_script.py) generating another python script (filegenerated.py)

So far i have created generate_script.py:

import os
fil         


        
4条回答
  •  北恋
    北恋 (楼主)
    2021-02-07 11:11

    You could just use a multiline string:

    import os
    filepath = os.getcwd()
    def MakeFile(file_name):
        temp_path = filepath + file_name
        with open(file_name, 'w') as f:
            f.write('''\
    def print_success():
        print "sucesss"        
    ''')
        print 'Execution completed.'
    

    If you like your template code to be indented along with the rest of your code, but dedented when written to a separate file, you could use textwrap.dedent:

    import os
    import textwrap
    
    filepath = os.getcwd()
    def MakeFile(file_name):
        temp_path = filepath + file_name
        with open(file_name, 'w') as f:
            f.write(textwrap.dedent('''\
                def print_success():
                    print "sucesss"        
                    '''))
        print 'Execution completed.'
    

提交回复
热议问题