如何在python中继续写入字符串

2024-04-26 01:00:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我用python写过这样的东西

script = """
    import network
    from machine import Pin, PWM
    from time import sleep
"""

我想在它后面写一些东西,但不删除旧的。我该怎么办?你知道吗


Tags: fromimporttimepinscriptsleepnetworkmachine
2条回答

您可以将一个字符串附加到一个字符串,如下所示

>>> script = """
...     import network
...     from machine import Pin, PWM
...     from time import sleep
... """
>>> script += "\nimport os"

您可以将脚本放入template中,然后填充值。如果生成的脚本相当复杂,那么这可能比连接字符串更容易管理。你知道吗

# script.template
import network
from machine import Pin, PWM
from time import sleep

${xyz}

# script-generator.py
from string import Template

with open('script.template') as f:
    template = Template(f.read()

contents = template.substitute(xyz='xyz')

with open('main.py', 'w') as f:
    f.write(contents)

或者,如果一个单独的模板文件看起来像是过度杀戮,您也可以这样使用str.format()

script = """\
import network
from machine import Pin, PWM
from time import sleep

{xyz}
"""

data = {'xyz': 'xyz'}

with open('main.py', 'w') as f:
    f.write(script.format(**data))

相关问题 更多 >