首页 文章

Python打印字符串到文本文件

提问于
浏览
458

我正在使用Python打开文本文档:

text_file = open("Output.txt", "w")

text_file.write("Purchase Amount: " 'TotalAmount')

text_file.close()

我想在文本文档中输入名为“TotalAmount”的字符串 . 有人可以让我知道怎么做吗?

7 回答

  • 886

    如果您使用的是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()
    
  • 9

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

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

    price = 33.3
    with open("Output.txt", "w") as text_file:
        text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))
    

    更多:Print multiple arguments in python

  • 0
    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)
    

    如果你're using Python2.6 or higher, it'首选使用 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-strings作为另一种选择

    with open("Output.txt", "w") as text_file:
        print(f"Purchase Amount: {TotalAmount}", file=text_file)
    
  • 16

    在Linux和Python中更容易的方法,

    import os
    string_input = "Hello World"
    os.system("echo %s > output_file.txt" %string_input)
    

    (要么)

    import os
    string_input = "Hello World"
    os.system("echo %s | tee output_file.txt" %string_input)
    
  • 4

    我认为更简单的方法是使用将要设置的文本附加到文件中

    open('file_name','a')

    这是一个例子

    file=open('file','a')
    file.write("Purchase Amount: " 'TotalAmount')
    file.close()
    

    “a”指的是附加情绪,它会将您要写入的文本附加到文件中文本的末尾

  • 0

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

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

相关问题