Python打印string到文本文件

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

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

我想在文本文件中input名为“TotalAmount”的string。 有人可以让我知道如何做到这一点?

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

如果您使用上下文pipe理器,该文件会自动closures

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

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

Python3.6引入了fstring作为另一种select

 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)) 

更多: 在Python中打印多个参数

这是Python打印string到文本文件的例子

 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, 'wb') as x_file: x_file.write('{} TotalAmount'.format(data)) def run(): data = my_func() write_file(data) run() 

如果您使用的是numpy,则只需要一行就可以将一个(或多个)string打印到一个文件中:

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