比较来自世界各地的卖家的域名和 IT 服务价格

文本文件中的打印字符串

我用 Python 要打开文本文档:


text_file = open/"Output.txt", "w"/

text_file.write/"Purchase Amount: " 'TotalAmount'/

text_file.close//


我想替换字符串变量的值
TotalAmount

在文本文档中。 有人可以让我知道如何做到这一点吗?
已邀请:

江南孤鹜

赞同来自:

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 有一个可选的参数
file

对于功能
print



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


Python3.6 介绍
https://docs.python.org/3/what ... erals
另一个替代方案


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

风见雨下

赞同来自:

如果要传输多个参数,则可以使用元组


price = 33.3
with open/"Output.txt", "w"/ as text_file:
text_file.write/"Purchase Amount: %s price %f" % /TotalAmount, price//


阅读更多:
https://coderoad.ru/15286401/

八刀丁二

赞同来自:

如果您正在使用 Python3.

然后你可以使用
https://docs.python.org/3/libr ... print
:


your_data = {"Purchase Amount": 'TotalAmount'}
print/your_data, file=open/'D:\log.txt', 'w'//


为了 python2

这就是一个例子 Python 在文本文件中显示字符串


def my_func//:
"""
this function return some value
:return:
"""
return 25.256


def write_file/data/:
"""
this function write data to file
:param data:
:return:
"""
file_name = r'D:\log.txt'
with open/file_name, 'w'/ as x_file:
x_file.write/'{} TotalAmount'.format/data//


def run//:
data = my_func//
write_file/data/


run//

二哥

赞同来自:

如果您正在使用 numpy, 打印一 /或几个/ 文件中的字符串只能使用相同的行执行:


numpy.savetxt/'Output.txt', ["Purchase Amount: %s" % TotalAmount], fmt='%s'/

喜特乐

赞同来自:

使用模块时 pathlib 缩进不是必需的。


import pathlib
pathlib.Path/"output.txt"/.write_text/"Purchase Amount: {}" .format/TotalAmount//


以。。。开始 python 3.6, F线可用。


pathlib.Path/"output.txt"/.write_text/f"Purchase Amount: {TotalAmount}"/

要回复问题请先登录注册