python - 将字符串打印到文本文件

标签 python string text file-io

我正在使用 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中,print函数有一个可选的file参数

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

Python3.6 引入f-strings另一种选择

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

关于python - 将字符串打印到文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5214578/

相关文章:

Python 方法 : modify original vs return a different object

python - 如何使用 python 生成规则的地理网格?

python - 导入 JavascriptExecutor (Selenium)

string - 当指标缓冲区不再给出值时,如何保持字符串值相同?

python - 将字符串的可变大小部分保存到另一个变量

c - 从 C 文本文件中读取值流

javascript - 如何使用Javascript检查文本是否被CSS chop

python - 使用代理扭曲 getpage

java - 这种 Java 加密方法的等效 PHP 解密是什么?

java - 根据按钮/标签大小调整文本大小