Answers:
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引入了f字符串作为另一种选择
with open("Output.txt", "w") as text_file:
print(f"Purchase Amount: {TotalAmount}", file=text_file)
TotalAmount
是int
,要么%d
还是%s
会做同样的事情。
with . . .: print('{0}'.format(some_var), file=text_file)
抛出:SyntaxError: invalid syntax
等号...
from __future__ import print_function
文件顶部。请注意,这会将文件中的所有打印语句转换为较新的函数调用。
如果要传递多个参数,可以使用元组
price = 33.3
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))
如果您使用的是Python3。
然后可以使用打印功能:
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()