我有一系列文件,其中包含以 {myvar}
形式定义的许多变量。例如
文件.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)
关于python - 如何以格式化字符串打开文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56116599/