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

发布于 2021-02-02 23:15:37

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

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

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

text_file.close()

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

关注者
0
被浏览
91
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。
    text_file = open("Output.txt", "w")
    text_file.write("Purchase Amount: %s" % TotalAmount)
    text_file.close()
    

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

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

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

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

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

    在Python3中,fileprint函数有一个可选参数

    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)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看