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

Sos*_*osi 6 python string file python-3.x

我有一系列文件,{myvar}里面有很多在表单中定义的变量。例如

文件.txt

This is {myvar}.
Run Code Online (Sandbox Code Playgroud)

我想打开它们,并正常替换变量:

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


myvar='myself.'
print(f"{myfile}")
Run Code Online (Sandbox Code Playgroud)

应该输出:

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


myvar='myself.'
print(f"{myfile}")
Run Code Online (Sandbox Code Playgroud)

如何将文件作为格式化字符串打开?或者将字符串转换为格式化字符串?

mar*_*eau 9

如果变量是调用的本地变量,这似乎有效,如果它是全局变量,请使用**globals(). 您还可以将值放入以变量名作为键的字典中。

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)
Run Code Online (Sandbox Code Playgroud)