简体   繁体   English

如何编写程序刚刚生成的python文件?

[英]How to write a python file just generated by the program?

I would like to know how do I write something in python file my program is generating.我想知道如何在我的程序生成的 python 文件中写一些东西。 Here we have: hey.py and main.py .这里我们有: hey.pymain.py In hey.py there is:在 hey.py 中有:

import main

start = f"print('Hello {NAME}')\n print('or world')",

In the main.py I have:在 main.py 我有:

import hey

NAME = input("Before starting , what is your name ? \n")
    namefile = input("okay , what should be the main file title ? \n")
    with open(namefile+".py", 'w') as f:
        f.write('{}'.format(start))

I would like to find in my python file just generated:我想在我刚刚生成的 python 文件中找到:

Hello Josh
or world

But unfortunately, my program can create the file but can't write in it:/但不幸的是,我的程序可以创建文件但不能写入:/

It's saying:它在说:

f.write('{}'.format(start))
NameError: name 'start' is not defined

Start is defined in hey.py.开始在 hey.py 中定义。 I imported.我进口的。 Have you any solution?你有什么解决办法吗? Thanks for answering.谢谢回答。

Couple of problems:几个问题:

  1. If importing like you have here, you need to use main.NAME and hey.start .如果像这里一样导入,则需要使用main.NAMEhey.start

  2. You're importing hey.py from main.py , and hey.py imports main.py .您从main.py hey.pyhey.py导入main.py When a script is imported in Python, it is essentially run from top to bottom.在 Python 中导入脚本时,基本上是从上到下运行的。 This means that hey.start is only defined in hey.py after main.py is run, but main.py requires variables local to hey.py , specifically hey.start .这意味着hey.start仅在hey.py运行后在main.py中定义,但main.py需要hey.py的本地变量,特别是hey.start The line that defines this variable hasn't been executed by the time main.py needs it.main.py需要它的时候,定义这个变量的行还没有被执行。

Solution for the second problem is to remove import main and define第二个问题的解决方法是去掉import main并定义

start = "print('hello {}')\n print('or world')"

instead.反而。 Then the formatting can be done in main.py as f.write(hey.start.format(NAME)然后格式化可以在main.py中作为f.write(hey.start.format(NAME)

Maybe this code can be useful for you.也许这段代码对你有用。

def create_file(namefile, text):
   pyfile = open(namefile,'r+')
   pyfile.write(text)
   pyfile.close()

create_file('example.py', 'print("{}")\nprint("{}")'.format('Hello Jhon','I am Joao from Peru'))

then run example.py然后运行 example.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM