import pathlib
file_name = '%s/survey_ids.txt' % pathlib.Path(__file__).parent.resolve()
f = open(file_name, "a ")
f.write("hello world\n")
print(f.read())
f.close()
我第一次運行腳本時,它會創建檔案survey_ids.txt并寫入檔案hello world\n。它肯定不會列印任何東西。但是我第二次運行它時,它寫了另一個hello world\n,survey_ids.txt但仍然沒有列印任何東西。我想它會列印出來hello world\n。為什么會發生這種情況?
uj5u.com熱心網友回復:
f.write推進流位置。因此,當您使用f.read()它讀取檔案時,它將嘗試從當前流位置讀取到檔案末尾。要獲得預期的行為,請在呼叫之前嘗試seek位元組偏移 0 。.read
f = open("test.txt", "a ")
f.write("hello world\n")
f.seek(0)
print(f.read())
f.close()
同樣正如評論中所建議的,最好使用背景關系管理器,它會自動清理資源。
uj5u.com熱心網友回復:
當您使用a mode 打開檔案時,檔案流將位于檔案末尾。在創建 DictReader 之前呼叫f.seek( 0 )其中 f 是創建的檔案物件。open( ... )有關此問題的更詳細討論,請參閱此問題。
f = open("test.txt", "a ")
f.write("hello world\n")
f.seek(0)
print(f.read())
f.close()
和開放
with open(file_name, "a ") as f:
f.write("hello world\n")
f.seek(0)
print(f.read())
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/414150.html
標籤:
上一篇:MongoDB$查找物件陣列
