【问题标题】:Print string to text file将字符串打印到文本文件
【发布时间】:2011-07-10 00:45:56
【问题描述】:

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

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

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

text_file.close()

我想将字符串变量TotalAmount 的值替换到文本文档中。有人可以告诉我该怎么做吗?

【问题讨论】:

  • 你为什么不做w+

标签: python string text file-io


【解决方案1】:

如果您需要将较长的 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(item+ '\n'+ '\n')

f.close()

【讨论】:

    【解决方案2】:

    强烈建议使用上下文管理器。作为一个优势,它确保文件始终处于关闭状态,无论如何:

    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)
    

    【讨论】:

    • 假设 TotalAmount 是一个整数,“%s”不应该是“%d”吗?
    • @RuiCurado,如果TotalAmountint,则%d%s 都会做同样的事情。
    • 很好的答案。我看到一个几乎相同用例的语法错误:with . . .: print('{0}'.format(some_var), file=text_file) is throwing: SyntaxError: invalid syntax at the equal sign...
    • @nicorellius,如果你想在 Python2.x 中使用它,你需要把 from __future__ import print_function 放在文件的顶部。请注意,这会将文件中的 所有 打印语句转换为较新的函数调用。
    • 为了确保知道变量类型是什么,经常转换它以确保,例如:“text_file.write('Purchase Amount: %s' % str(TotalAmount))”,它将与列表一起使用、字符串、浮点数、整数以及任何其他可转换为字符串的内容。
    【解决方案3】:

    使用f-string 是一个不错的选择,因为我们可以将multiple parametersstr 这样的语法相结合,

    例如

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

    【讨论】:

      【解决方案4】:

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

      【讨论】:

      • 你为什么不做w+
      • print(your_data, file=open(...)) 将保持文件打开
      • python 3 的最佳答案,因为您可以利用打印功能的特性。您不需要映射到 str 和连接元素,只需将每个元素作为参数打印,然后让 print 函数完成其余的工作。例如: print(arg, getattr(args, arg), sep=", ", file=output)
      【解决方案5】:

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

      【讨论】:

        【解决方案6】:

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

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

        【讨论】:

          【解决方案7】:

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

          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

          【讨论】:

          • 你为什么不做w+
          • 只是偏好,我喜欢区分何时写入和读取文件。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-04
          • 2020-01-12
          • 1970-01-01
          • 2012-11-05
          相关资源
          最近更新 更多