我正在使用Python打开文本文档:
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: " 'TotalAmount')
text_file.close()
我想将字符串变量TotalAmount
的值替换为文本文档。有人可以告诉我怎么做吗?
答案 0 :(得分:1015)
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-stringswith open("Output.txt", "w") as text_file:
print(f"Purchase Amount: {TotalAmount}", file=text_file)
答案 1 :(得分:32)
如果您想传递多个参数,可以使用元组
price = 33.3
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))
答案 2 :(得分:18)
如果您使用的是Python3。
然后您可以使用Print Function:
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()
答案 3 :(得分:16)
如果你正在使用numpy,只需一行即可将单个(或多个)字符串打印到文件中:
numpy.savetxt('Output.txt', ["Purchase Amount: %s" % TotalAmount], fmt='%s')
答案 4 :(得分:7)
使用pathlib模块时,不需要缩进。
import pathlib
pathlib.Path("output.txt").write_text("Purchase Amount: {}" .format(TotalAmount))
从python 3.6开始,f-strings可用。
pathlib.Path("output.txt").write_text(f"Purchase Amount: {TotalAmount}")
答案 5 :(得分:1)
使用 f-string
是一个不错的选择,因为我们可以将 multiple parameters
放在 str
之类的语法中,
例如:
import datetime
now = datetime.datetime.now()
price = 1200
currency = "INR"
with open("D:\\log.txt","a") as f:
f.write(f'Product sold at {currency} {price } on {str(now)}\n')