Using “with open() as file” method, how to write more than once?
本问题已经有最佳答案,请猛点这里访问。
通常,为了写一个文件,我会做以下操作:
1 2 | the_file = open("somefile.txt","wb") the_file.write("telperion") |
但出于某种原因,伊普敦(Jupyter)没有写这些文件。这很奇怪,但我唯一能让它工作的方法就是这样写:
1 2 3 4 5 6 7 | with open('somefile.txt',"wb") as the_file: the_file.write("durin's day ") with open('somefile.txt',"wb") as the_file: the_file.write("legolas ") |
但很明显,它将重新创建文件对象并重写它。
为什么第一个块中的代码不起作用?第二个街区怎么走?
另外,您似乎正在使用python 2。您不应该使用
因此:
1 2 3 4 5 6 7 | with open('somefile.txt', 'a') as the_file: the_file.write("durin's day ") with open('somefile.txt', 'a') as the_file: the_file.write("legolas ") |
对于使用