一週前開始Python,我有一些問題需要關於讀取和寫入相同的文件。我在網上瀏覽了一些教程,但我仍然對此感到困惑。我可以理解簡單的讀寫文件。初學者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 readFile
openFile.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 readFile
openFile.close()
如果有人能告訴我我在這裏做錯了什麼,或者它只是一個Pythong的事情,我將不勝感激。我正在使用Python 2.7。謝謝!
這是奇怪的部分。如果我嘗試這些行,似乎出現錯誤:f = open(「C:\ Users \ MooMoo \ Desktop \ clothes.txt」,「r +」)012.fmtoooooooooo 「)。我得到的錯誤信息:Traceback(最近一次調用最後一次): 文件「C:\ Users \ MooMoo \ Desktop \ Python27 \ PyProject \ src \ test.py」,第43行, f.write(「foooooooooooooo」 ) IOError:[Errno 0] Error f.close() –
Cryssie
這看起來像是一個特定於Windows的問題。我正在更新我的回覆。要點:在寫之前使用f.seek(f.tell())。 – sidi