一周前開始使用Python,我有一些關于讀寫相同文件的問題。我已經在線閱讀了一些教程,但對此仍然感到困惑。我可以理解簡單的讀寫文件。openFile = open("filepath", "r")readFile = openFile.read()print readFile openFile = open("filepath", "a")appendFile = openFile.write("\nTest 123")openFile.close()但是,如果我嘗試以下操作,則會在要寫入的文本文件中得到一堆未知文本。誰能解釋我為什么會收到這樣的錯誤,以及為什么我不能以如下所示的方式使用相同的openFile對象。# I get an error when I use the codes below: openFile = open("filepath", "r+")writeFile = openFile.write("Test abc")readFile = openFile.read()print readFileopenFile.close()我將嘗試澄清我的問題。在上面的示例中,openFile是用于打開文件的對象。如果我想第一次寫它,我沒有問題。如果我想使用相同的openFile來讀取文件或向其附加內容。它不會發生或給出錯誤。我必須聲明相同/不同的打開文件對象,然后才能對同一文件執行另一個讀/寫操作。#I have no problems if I do this: openFile = open("filepath", "r+")writeFile = openFile.write("Test abc")openFile2 = open("filepath", "r+")readFile = openFile2.read()print readFileopenFile.close()如果有人能告訴我我在這里做錯了還是僅僅是Pythong的事情,我將不勝感激。我正在使用Python 2.7。謝謝!
初學者Python:讀取和寫入同一文件
慕田峪7331174
2019-11-19 09:57:40