将字符串输出到文本文件

898

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

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

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

text_file.close()

我想将字符串变量TotalAmount的值替换到文本文档中,请问有人能告诉我如何做到这一点吗?


你为什么没有使用 w+ - Charlie Parker
8个回答

1607

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

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中,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)

2
假设TotalAmount是一个整数,那么"%s"不应该改成"%d"吗? - Rui Curado
6
如果TotalAmount是一个整型变量,那么使用%d或者%s都可以达到同样的效果。 - John La Rooy
2
很好的答案。我看到一个语法错误,与一个几乎相同的用例相关:with . . .: print('{0}'.format(some_var), file=text_file) 在等号处抛出了 SyntaxError: invalid syntax - nicorellius
4
如果您想在Python2.x中使用该功能,您需要在文件顶部添加from __future__ import print_function。请注意,这将会将文件中的所有print语句转换为更新的函数调用形式。 - John La Rooy
我需要找到一个我曾经成功解决这个问题的例子。我可能误解了问题和解决方案。你说的很有道理。 - EBo
显示剩余5条评论

63

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

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

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


你为什么没有使用 w+ - Charlie Parker
只是个人偏好,我喜欢区分我是在写入还是读取文件。 - user1767754

49

如果您正在使用Python3.

那么你可以使用Print函数

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

你为什么没有使用w+ - Charlie Parker
5
print(your_data, file=open(...))会使文件保持打开状态。 - Mikhail
Python 3 的最佳答案是因为您可以利用 print 函数的特性。您不需要映射到 str 并连接元素,只需将每个元素作为参数提供给 print 并让 print 函数来完成其余的工作。例如:print(arg, getattr(args, arg), sep=", ", file=output) - ibilgen

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

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 是一个不错的选择,因为我们可以用类似 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字符串分割成较小的字符串,并将它们添加到以新行\n分隔的.txt文件中,请使用下面的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()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接