我有一系列文件,其中有许多以{myvar}
形式定义的变量。例如
file.txt
This is {myvar}.
我想打开它们,并让变量正常替换:
with open('path/to/file.txt', 'r') as file:
myfile = file.read().replace('\n', '')
myvar='myself.'
print(f"{myfile}")
应该输出:
This is myself.
如何以格式化字符串打开文件?还是将字符串转换为格式化的字符串?
最佳答案
如果变量是调用的局部变量,则这似乎可行;如果它是全局变量,请使用**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)