将字符串打印到文本文件 [英] Print string to text file

查看:104
本文介绍了将字符串打印到文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Python to open a text document:

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

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

text_file.close()

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

I want to substitute the value of a string variable TotalAmount into the text document. Can someone please let me know how to do this?

推荐答案

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

如果使用上下文管理器,则将自动为您关闭文件

If you use a context manager, the file is closed automatically for you

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

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

If you're using Python2.6 or higher, it's preferred to use str.format()

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

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

For python2.7 and higher you can use {} instead of {0}

在Python3中,print函数有一个可选的file参数

In Python3, there is an optional file parameter to the print function

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

Python3.6引入了 f字符串另一种选择

Python3.6 introduced f-strings for another alternative

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

这篇关于将字符串打印到文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆