将字符串打印到文本文件[重复]

2023-11-30

我正在使用 Python 打开一个文本文档:

text_file = open("Output.txt", "w")

text_file.write("Purchase Amount: " 'TotalAmount')

text_file.close()

我想替换字符串变量的值TotalAmount到文本文档中。有人可以让我知道该怎么做吗?


强烈建议使用上下文管理器。一个优点是,无论发生什么情况,都可以确保文件始终关闭:

with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: %s" % TotalAmount)

这是显式版本(但永远记住,上面的上下文管理器版本应该是首选):

text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()

如果您使用的是Python2.6或更高版本,最好使用str.format()

with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: {0}".format(TotalAmount))

对于 python2.7 及更高版本,您可以使用{}代替{0}

在Python3中,有一个可选的file参数到print功能

with open("Output.txt", "w") as text_file:
    print("Purchase Amount: {}".format(TotalAmount), file=text_file)

Python3.6引入F 弦另一种选择

with open("Output.txt", "w") as text_file:
    print(f"Purchase Amount: {TotalAmount}", file=text_file)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将字符串打印到文本文件[重复] 的相关文章

随机推荐