【问题标题】:Writing to file using Python [duplicate]使用 Python 写入文件 [重复]
【发布时间】:2016-02-15 01:59:19
【问题描述】:

我有一个名为 output.txt 的文件,我想从代码周围的几个函数中写入该文件,其中一些是递归的。 问题是,每次我写的时候,我都需要一次又一次地打开文件,然后我之前写的所有东西都被删除了。 我很确定有一个解决方案,但在之前提出的所有问题中都没有找到它..

def CutTable(Table, index_to_cut, atts, previousSv, allOfPrevSv):
    print ('here we have:')
    print atts
    print index_to_cut
    print Table[2]
    tableColumn=0
    beenHere = False
    for key in atts:
        with open("output.txt", "w") as f:
            f.write(key)

从另一个函数:

def EntForAttribute(possibles,yesArr):
svs = dict()
for key in possibles:
    svs[key]=(yesArr[key]/possibles[key])
for key in possibles:
        with open("output.txt", "w") as f:
            f.write(key)

我的所有输出都是用其中一个函数编写的最后一个。

【问题讨论】:

  • 以追加模式打开文件。 open("output.txt", "a")
  • 传递 f 或使其全局化
  • 当我在做这样的事情时,最初需要一个写入然后很多附加,我通常会做这样的事情:with open('file.txt', 'w' if not os.path.isfile('file.txt') else 'a') as f:
  • @Tgsmith61591 与open('file.txt', 'a') 的功能有何不同?

标签: python file writefile


【解决方案1】:

打开文件时需要更改第二个标志:

  • w 仅用于写入(同名的现有文件将 删除)
  • a 打开文件进行追加

你的代码应该是:

with open("output.txt", "a") as f:

【讨论】:

    【解决方案2】:

    每次您进入和退出with open... 块时,您都在重新打开文件。正如其他答案所提到的,您每次都在覆盖文件。除了切换到追加之外,交换 withfor 循环可能是一个好主意,这样您只需为每组写入打开一次文件:

    with open("output.txt", "a") as f:
        for key in atts:
            f.write(key)
    

    【讨论】:

      【解决方案3】:

      我相信你需要像这样以附加模式打开文件(在这里回答:append to file in python):

      with open("output.txt", "a") as f:
          ## Write out
      

      【讨论】:

        【解决方案4】:

        简短的回答。将文件描述符中的“w”更改为“a”以进行追加。

        with open("test.txt", "a") as myfile:
            myfile.write("appended text")
        

        这已经在这个线程中得到了回答。 How do you append to a file?

        【讨论】:

          猜你喜欢
          • 2011-06-10
          • 1970-01-01
          • 2016-12-07
          • 2018-12-05
          • 1970-01-01
          • 2013-04-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多