【问题标题】:How to write to multiple files in Python?如何在 Python 中写入多个文件?
【发布时间】:2015-09-12 14:29:54
【问题描述】:

我有两个文件要打开:

file = open('textures.txt', 'w')
file = open('to_decode.txt', 'w')

那我想分别写给他们两个:

file.write("Username: " + username + " Textures: " + textures)
file.write(textures)

第一次写东西是为了第一次打开,第二次是为了第二次。 我该怎么做?

【问题讨论】:

  • 你有什么尝试吗?
  • 使用两个不同的变量名。 file 也是一个糟糕的选择。它是 Python 2 中内置函数的名称。
  • file1 和 file2 或者您可以编写一个函数并在函数中进行打开和写入,这样您就不必重复自己...

标签: python file writing


【解决方案1】:

您将在第二次打开时覆盖file 变量,因此所有写入都将定向到那里。相反,您应该使用两个变量:

textures_file = open('textures.txt', 'w')
decode_file = open('to_decode.txt', 'w')

textures_file.write("Username: " + username + " Textures: " + textures)
decode_file.write(textures)

【讨论】:

    【解决方案2】:

    为你的文件指针命名两个不同的东西,即不是两个“文件”。

    file1 = open...
    file2 = open...
    
    file1.write...
    file2.write...
    

    现在,您所做的第二个“文件”声明正在覆盖第一个,因此文件仅指向“to_decode.txt”。

    【讨论】:

      【解决方案3】:

      给他们不同的名字:

      f1 = open('textures.txt', 'w')
      f2 = open('to_decode.txt', 'w')
      
      f1.write("Username: " + username + " Textures: " + textures)
      f2.write(textures)
      

      正如其他人所提到的,file 是内置函数的名称,因此使用该名称作为局部变量是一个不好的选择。

      【讨论】:

        【解决方案4】:

        正如@Klaus 所说,您需要使用两个不同的变量来创建两个不同的、不同的句柄,您可以将操作推送到这些句柄。所以,

        file1 = open('textures.txt', 'w')
        file2 = open('to_decode.txt', 'w')
        

        然后

        file1.write("Username: " + username + " Textures: " + textures)
        file2.write(textures)
        

        【讨论】:

          【解决方案5】:

          您可以使用“with”来避免明确提及 file.close()。然后您不必关闭它 - Python 会在垃圾收集期间或程序退出时自动执行此操作。

          with open('textures.txt', 'w') as file1,open('to_decode.txt', 'w') as file2:
          
              file1.write("Username: " + username + " Textures: " + textures)
              file2.write(textures)
          

          【讨论】:

          • 然而with 的主要优点是即使发生错误也会自动关闭文件句柄。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-11-12
          • 1970-01-01
          • 2017-09-03
          • 2022-11-03
          相关资源
          最近更新 更多