python打印文件到字符串_Python打印字符串到文本文件

我正在使用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中,print函数有一个可选的file参数。

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是一个整数,"%s"不应该是一个"%d"吗?

@如果TotalAmount是int的话,那么%d或%s也会做同样的事情。

很好的回答。我看到了一个几乎相同的用例的语法错误:with . . .: print('{0}'.format(some_var), file=text_file)正在抛出:SyntaxError: invalid syntax在等号处…

@Nicorellius,如果你想和python2.x一起使用,你需要把from __future__ import print_function放在文件的顶部。请注意,这将把文件中的所有print语句转换为较新的函数调用。

谢谢。我感到困惑的原因是我的虚拟环境使用的是python 3.x。我在fabfile中运行了一些调试代码,当然,它使用的是系统python,例如2.7。我忽略了这个结构还不支持python 3。

要确保知道变量类型通常是什么,请将其转换为确保,例如:"text_file.write('purchase amount:%s'%str(totalamount))",它将与列表、字符串、浮点、int以及其他可转换为字符串的内容一起使用。

@EBO,格式字符串在不同语言中的工作方式略有不同。在python中,%s表示调用obj.__str__。所以它的行为和明确地调用str是相同的。

同意,但在飞行中,有时很难知道当诊断语句出现故障时要改变什么。另外,当我试图与变量类型保持一致时,没有任何保证。

@但它是有保证的。如果%s不能转换成str,那么str()也不能。如果这还不清楚,也许你可以提出一个新的问题。

我必须找到一个对我有用的例子。我可能误解了这个问题和有效的解决方案。你说的话是有道理的。

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

price = 33.3

with open("Output.txt","w") as text_file:

text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))

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

这就像print。

如果使用numpy,只需一行即可将单个(或多个)字符串打印到文件:

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

If you are using Python3.

然后可以使用打印功能:

your_data = {"Purchase Amount": 'TotalAmount'}

print(your_data,  file=open('D:\log.txt', 'w'))

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

使用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}")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值