通常寫一個文件,我將做到以下幾點:使用「with open()as file」方法,如何多次寫入?
the_file = open("somefile.txt","wb")
the_file.write("telperion")
但出於某種原因,IPython中(Jupyter)不是寫文件。這是很奇怪,但我可以得到它的工作的唯一辦法是,如果我這樣寫:
with open('somefile.txt', "wb") as the_file:
the_file.write("durin's day\n")
with open('somefile.txt', "wb") as the_file:
the_file.write("legolas\n")
但很明顯,這將重新創建該文件的對象,並重寫。
爲什麼第一個程序段中的代碼不起作用?我怎麼能讓第二塊工作?
以「w」模式打開文件會刪除文件中的所有數據(如果存在)。 –
嘗試:'the_file = open(「somefile.txt」,「wb」,buffering = False)'。 –
讓我們回到您原來的寫作。寫入數據會被緩存,直到您寫入數據塊或關閉文件。所以你可能還沒有看到磁盤上的數據。 – tdelaney