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

标签 python python-3.x string file

我有一系列文件,其中包含以 {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/

相关文章:

python - 如果 python 中的 block 未使用 True 语句执行

string - F# 中字符串的编译时约束,类似于度量单位 - 是否可能?

python - 喀拉斯 : Implementing a custom metric with logical operators

python - 为什么 while 循环中的缩进会产生问题?

python - 以有效的方式从列表中消除特定元素的函数

python - 自动导入模块

regex - 如果文本只包含一次字符串,则匹配该文本的正则表达式

python sqlite3 插入列表

python - Pandas :通过 "Column A"应用函数,同时读取 "Column B"

python - mac - pip 安装 pymssql 错误