The*_*Woo 590 python string file-io text
我正在使用Python打开文本文档:
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: " 'TotalAmount')
text_file.close()
Run Code Online (Sandbox Code Playgroud)
我想将字符串变量的值替换TotalAmount为文本文档.有人可以让我知道怎么做吗?
Joh*_*ooy 1120
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()
Run Code Online (Sandbox Code Playgroud)
如果您使用上下文管理器,则会自动关闭该文件
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s" % TotalAmount)
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Python2.6或更高版本,则首选使用 str.format()
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: {0}".format(TotalAmount))
Run Code Online (Sandbox Code Playgroud)
对于python2.7及更高版本,您可以使用{}而不是{0}
在Python3中,函数有一个可选file参数print
with open("Output.txt", "w") as text_file:
print("Purchase Amount: {}".format(TotalAmount), file=text_file)
Run Code Online (Sandbox Code Playgroud)
Python3.6 为另一种选择引入了f-strings
with open("Output.txt", "w") as text_file:
print(f"Purchase Amount: {TotalAmount}", file=text_file)
Run Code Online (Sandbox Code Playgroud)
use*_*754 36
如果您想传递多个参数,可以使用元组
price = 33.3
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))
Run Code Online (Sandbox Code Playgroud)
Raj*_*rma 22
如果您使用的是Python3.
然后你可以使用打印功能:
your_data = {"Purchase Amount": 'TotalAmount'}
print(your_data, file=open('D:\log.txt', 'w'))
Run Code Online (Sandbox Code Playgroud)
对于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()
Run Code Online (Sandbox Code Playgroud)
Guy*_*y s 16
如果您正在使用numpy,只需一行就可以将单个(或多个)字符串打印到文件中:
numpy.savetxt('Output.txt', ["Purchase Amount: %s" % TotalAmount], fmt='%s')
Run Code Online (Sandbox Code Playgroud)
使用pathlib模块时,不需要缩进.
import pathlib
pathlib.Path("output.txt").write_text("Purchase Amount: {}" .format(TotalAmount))
Run Code Online (Sandbox Code Playgroud)
从python 3.6开始,f-strings可用.
pathlib.Path("output.txt").write_text(f"Purchase Amount: {TotalAmount}")
Run Code Online (Sandbox Code Playgroud)
我想很多人都使用这里的答案作为如何将字符串写入文件的一般快速参考。通常,当我将字符串写入文件时,我想指定文件编码,具体操作方法如下:
with open('Output.txt', 'w', encoding='utf-8') as f:
f.write(f'Purchase Amount: {TotalAmount}')
Run Code Online (Sandbox Code Playgroud)
如果您不指定编码,则使用的编码取决于平台(请参阅文档)。我认为从实际角度来看,默认行为很少有用,并且可能会导致严重的问题。这就是为什么我几乎总是设置encoding参数。
| 归档时间: |
|
| 查看次数: |
1101410 次 |
| 最近记录: |