我将带有函数调用的 f 字符串存储在一个单独的文件中(有很多变量)。
我正在编写一个脚本,其中包含数百个变量,然后将这些变量加载到 HTML 表格中。 HTML 表格中的某些内容需要函数调用。
这个有效:
def add_one(a):
return a + 1
a = 1
s = f"A is {a} and next comes {add_one(a)}"
print(s)
当我将 s
存储在一个文件中时,我可以使用 **locals()
对其进行格式化,当我将变量存储在 s.txt 中时它会起作用。
s.txt 的内容:
A is {a}
有效的脚本内容:
a = 1
print(open('s.txt').read().format(**locals()))
但是,当我尝试调用函数时,它不起作用:
s.txt 的内容:
A is {a} and next comes {add_one(a)}
不起作用的脚本内容:
def add_one(a):
return a + 1
a = 1
print(open('s.txt').read().format(**locals()))
我该怎么做才能让它发挥作用(考虑到我的实际情况是数百个函数调用,而不是这个简单的 2 变量示例)?
在这个例子中,它应该导致 A is 1 and next comes 2
。
最佳答案
如果您有一个包含数百个变量的复杂 HTML 表格,您可能需要考虑使用模板语言而不是 f 字符串。例如Jinja2 .
为简单起见,我将 a
值存储在字典中,这样可以简化将其传递给 Jinja2 渲染器并将其转换为 JSON 以将其存储在文件中的过程。
这是您使用 Jinja2 模板并将数据存储到 json 文件的示例:
import json
from pathlib import Path
import jinja2
json_file = Path('/tmp/test_store.json')
jinja_env = jinja2.Environment()
# Set variable values
values = {'a': 3}
# Save to json file
json_file.write_text(json.dumps(values))
# Read from json file to dictionary with new variable name
read_values = json.loads(json_file.read_text())
def add_one(a):
return a + 1
# Add custom filter to jinja environment
jinja_env.filters['add_one'] = add_one
# Define template
template = jinja_env.from_string("A is {{a}} and next comes {{a | add_one}}")
# Print rendered template
print(template.render(read_values))
这给出了输出:
A is 3 and next comes 4
JSON 文件如下:
{"a": 3}
关于python - 在文件中存储带有函数调用的 f 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75047028/