简体   繁体   English

如何以格式化字符串打开文件?

[英]How to open file as formatted string?

I have a series of files with lots of variables defined in the form {myvar} inside. 我有一系列文件,其中包含许多以{myvar}形式定义的变量。 eg 例如

file.txt file.txt

This is {myvar}.

I want to open them, and have the variables being replaced normally: 我想打开它们,并让变量正常替换:

with open('path/to/file.txt', 'r') as file:
    myfile = file.read().replace('\n', '')


myvar='myself.'
print(f"{myfile}")

Should output: 应该输出:

This is myself.

How can I open the file as a formatted string? 如何以格式化字符串打开文件? Or convert the string to formatted string? 还是将字符串转换为格式化的字符串?

This seems to work if the variable is local to the call, if it's a global variable, use **globals() . 如果变量是调用的局部变量,则这似乎可行;如果它是全局变量,请使用**globals() You can also put the value in a dictionary that has the variable name as the key. 您也可以将值放在以变量名作为键的字典中。

myvar = 'myself'
newline = '\n'  # Avoids SyntaxError: f-string expr cannot include a backslash

with open('unformatted.txt', 'r') as file:
    myfile = f"{file.read().replace(newline, '')}".format(**locals())

print(myfile)

You are almost there. 你快到了

Assume there is "This is {myvar}." 假设有“这是{myvar}”。 in file.txt. 在file.txt中。

Coding: 编码:

with open('path/to/file.txt', 'r') as file:
    myfile = file.read().replace('\n', '')

myvar='myself'

print(myfile.format(myvar=myvar))

Any strings in plain text format, can be imported as a variable from a text file. 任何纯文本格式的字符串都可以从文本文件中作为变量导入。 Then the strings variable can be manipulated as normal. 然后可以正常操作strings变量。

In you case, the key is "{var}". 在这种情况下,键为“ {var}”。 So you can easily use ".format(var=varx) as long as you defined variable "varx". 因此,只要定义了变量“ varx”,就可以轻松使用“ .format(var = varx)”。

Output: 输出:

This is myself. 这是我自己

And if you want to import html template with css style and replace some contents, you can just use "{{" and "}}" to escape "{" and "}". 而且,如果您要导入具有CSS样式的html模板并替换某些内容,则只需使用“ {{”和“}}”转义“ {”和“}”即可。

Example 2 In file: 示例2在文件中:

This is {myvar} for a {{var}}. 这是{{var}}的{myvar}。

Output: 输出:

This is myself for a {var}. 这是我自己的{var}。

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

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