Python打印字符串到文本文件

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)

  • @RuiCurado,如果`TotalAmount`是一个`int`,`%d`或`%s`将做同样的事情. (6认同)
  • @nicorellius,如果你想在Python2.x中使用它,你需要在文件的顶部放置`from __future__ import print_function`.请注意,这会将文件中_all_的print语句转换为较新的函数调用. (4认同)
  • 假设TotalAmount是一个整数,那么"%s"不应该是"%d"吗? (2认同)
  • 很好的答案.我看到一个语法错误,几乎完全相同的用例:`with...:print('{0}'.format(some_var),file = text_file)`抛出:`SyntaxError:等号无效语法`... (2认同)

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)

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


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)

  • `print(your_data, file=open(...))` 将使文件保持打开状态 (2认同)

Guy*_*y s 16

如果您正在使用numpy,只需一行就可以将单个(或多个)字符串打印到文件中:

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


nao*_*ita 9

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


at5*_*321 6

我想很多人都使用这里的答案作为如何将字符串写入文件的一般快速参考。通常,当我将字符串写入文件时,我想指定文件编码,具体操作方法如下:

with open('Output.txt', 'w', encoding='utf-8') as f:
    f.write(f'Purchase Amount: {TotalAmount}')
Run Code Online (Sandbox Code Playgroud)

如果您不指定编码,则使用的编码取决于平台(请参阅文档。我认为从实际角度来看,默认行为很少有用,并且可能会导致严重的问题。这就是为什么我几乎总是设置encoding参数。