如何使用文本文件作为模板?

Luc*_*aga 3 python python-3.x

我想加载一个文本文件并用作 python 中的模板。

这是我的示例代码:

for x in range(1,10):
    tmp = open("test.md","r").read()
    print(tmp)
Run Code Online (Sandbox Code Playgroud)

这是我的文本文件 ( test.md):

for x in range(1,10):
    tmp = open("test.md","r").read()
    print(tmp)
Run Code Online (Sandbox Code Playgroud)

这是我当前的输出:

{ x }
Run Code Online (Sandbox Code Playgroud)

我想要这个输出:

{ x }
{ x }
{ x }
{ x }
{ x }
{ x }
{ x }
{ x }
{ x }
Run Code Online (Sandbox Code Playgroud)

Python 3 接受{ variable }字符串...在这种情况下我该怎么做?使用 f 字符串?

che*_*ner 7

您从文件中读取一个字符串;你需要调用它的format方法。

with open("test.md", "r") as f:
    tmp = f.read()

for x in range(1, 10):
    print(tmp.format(x))
Run Code Online (Sandbox Code Playgroud)

请注意,x模板中的 与循环中使用的变量名称无关for。

按原样,这将会失败,因为'{ x }'是与'{x}'. 编辑文件以提供有效的格式,修改内存中的模板(例如,tmp.replace(" ", "")),或在调用中提供准确的密钥format(tmp.format(**{" x ": x}))。