将字符串打印到文本文件[重复]

问题描述 投票:0回答:8

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

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

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

text_file.close()

我想将字符串变量

TotalAmount
的值替换到文本文档中。有人可以告诉我该怎么做吗?

python string text file-io
8个回答
1605
投票

强烈建议使用上下文管理器。一个优点是,无论发生什么情况,都可以确保文件始终关闭:

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

这是显式版本(但永远记住,上面的上下文管理器版本应该是首选):

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

如果您使用的是Python2.6或更高版本,最好使用

str.format()

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

对于 python2.7 及更高版本,您可以使用

{}
而不是
{0}

在Python3中,

file
函数有一个可选的
print
参数

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)

63
投票

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

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

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


48
投票

如果您使用的是Python3。

然后你就可以使用打印功能 :

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

32
投票

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

23
投票

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

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

4
投票

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

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

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

encoding
参数。


1
投票

使用

f-string
是一个不错的选择,因为我们可以将
multiple parameters
与类似
str
,

的语法放在一起

例如

import datetime

now = datetime.datetime.now()
price = 1200
currency = "INR"

with open("D:\\log.txt","a") as f:
    f.write(f'Product sold at {currency} {price } on {str(now)}\n')

0
投票

如果您需要将长 HTML 字符串拆分为较小的字符串,并将它们添加到由新行

.txt
分隔的
\n
文件中,请使用下面的 python3 脚本。 就我而言,我从服务器向客户端发送一个非常长的 HTML 字符串,并且我需要一个接一个地发送小字符串。 另外要小心 UnicodeError 如果您有特殊字符,例如水平条 或表情符号,您需要事先将它们替换为其他字符。 另请确保将 html 中的
""
替换为
''

#decide the character number for every division    
divideEvery = 100

myHtmlString = "<!DOCTYPE html><html lang='en'><title>W3.CSS Template</title><meta charset='UTF-8'><meta name='viewport' content='width=device-width, initial-scale=1'><link rel='stylesheet' href='https://www.w3schools.com/w3css/4/w3.css'><link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Lato'><link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css'><style>body {font-family: 'Lato', sans-serif}.mySlides {display: none}</style><body></body></html>"

myLength = len(myHtmlString)
division = myLength/divideEvery
print("number of divisions")
print(division)

carry = myLength%divideEvery
print("characters in the last piece of string")
print(carry)

f = open("result.txt","w+")
f.write("Below the string splitted \r\n")
f.close()

x=myHtmlString
n=divideEvery
myArray=[]
for i in range(0,len(x),n):
    myArray.append(x[i:i+n])
#print(myArray)

for item in myArray:
    f = open('result.txt', 'a')
    f.write('server.sendContent(\"'+item+'\");' '\n'+ '\n')

f.close()
© www.soinside.com 2019 - 2024. All rights reserved.