Python Print String To Text File

2018-12-31 23:11发布

I'm using Python to open a text document:

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

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

text_file.close()

I want to enter the string called "TotalAmount" into the text document. Can someone please let me know how to do this?

7条回答
浪荡孟婆
2楼-- · 2018-12-31 23:54

If you are using numpy, printing a single (or multiply) strings to a file can be done with just one line:

numpy.savetxt('Output.txt', ["Purchase Amount: %s" % TotalAmount], fmt='%s')
查看更多
无与为乐者.
3楼-- · 2018-12-31 23:58

Easier way to do in Linux and Python,

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

(OR)

import os
string_input = "Hello World"
os.system("echo %s | tee output_file.txt" %string_input)
查看更多
听够珍惜
4楼-- · 2019-01-01 00:06
text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()

If you use a context manager, the file is closed automatically for you

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

If you're using Python2.6 or higher, it's preferred to use str.format()

with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: {0}".format(TotalAmount))

For python2.7 and higher you can use {} instead of {0}

In Python3, there is an optional file parameter to the print function

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

Python3.6 introduced f-strings for another alternative

with open("Output.txt", "w") as text_file:
    print(f"Purchase Amount: {TotalAmount}", file=text_file)
查看更多
美炸的是我
5楼-- · 2019-01-01 00:07

I think the easier way to do that is via appending the text you want to set to the file using

open('file_name','a')

here is an example for that

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

"a" refer to append mood , it will append the text you want to write to the end of the text in the your file

查看更多
听够珍惜
6楼-- · 2019-01-01 00:08

In case you want to pass multiple arguments you can use a tuple

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

More: Print multiple arguments in python

查看更多
看风景的人
7楼-- · 2019-01-01 00:09

With using pathlib module, indentation isn't needed.

import pathlib
pathlib.Path("output.txt").write_text("Purchase Amount: {}" .format(TotalAmount))

As of python 3.6, f-strings is available.

pathlib.Path("output.txt").write_text(f"Purchase Amount: {TotalAmount}")
查看更多
登录 后发表回答