Python Print String To Text File
我正在使用python打开文本文档:
1 2 3 4 5 | text_file = open("Output.txt","w") text_file.write("Purchase Amount:" 'TotalAmount') text_file.close() |
我想在文本文档中替换字符串变量
1 2 3 | text_file = open("Output.txt","w") text_file.write("Purchase Amount: %s" % TotalAmount) text_file.close() |
如果使用上下文管理器,文件将自动为您关闭。
1 2 | with open("Output.txt","w") as text_file: text_file.write("Purchase Amount: %s" % TotalAmount) |
如果您使用的是python2.6或更高版本,最好使用
1 2 | with open("Output.txt","w") as text_file: text_file.write("Purchase Amount: {0}".format(TotalAmount)) |
对于python2.7及更高版本,可以使用
在python3中,
1 2 | with open("Output.txt","w") as text_file: print("Purchase Amount: {}".format(TotalAmount), file=text_file) |
python3.6为另一种选择引入了F字符串
1 2 | with open("Output.txt","w") as text_file: print(f"Purchase Amount: {TotalAmount}", file=text_file) |
如果要传递多个参数,可以使用元组
1 2 3 | price = 33.3 with open("Output.txt","w") as text_file: text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price)) |
更多:在python中打印多个参数
如果使用numpy,只需一行即可将单个(或多个)字符串打印到文件:
1 | numpy.savetxt('Output.txt', ["Purchase Amount: %s" % TotalAmount], fmt='%s') |
If you are using Python3.
然后可以使用打印功能:
1 2 | your_data = {"Purchase Amount": 'TotalAmount'} print(your_data, file=open('D:\log.txt', 'w')) |
For python2
这是python打印字符串到文本文件的示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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() |
使用pathlib模块时,不需要缩进。
1 2 | import pathlib pathlib.Path("output.txt").write_text("Purchase Amount: {}" .format(TotalAmount)) |
从python 3.6开始,提供F字符串。
1 | pathlib.Path("output.txt").write_text(f"Purchase Amount: {TotalAmount}") |