我正在嘗試通過 readline 逐行讀取日志檔案。我很驚訝地觀察到以下行為(在解釋器中執行的代碼,但從檔案執行變體時也會發生同樣的情況):
f = open('myfile.log')
line = readline()
while line:
print(line)
line = f.readline()
# --> This displays all lines the file contains so far, as expected
# At this point, I open the log file with a text editor (Vim),
# add a line, save and close the editor.
line = f.readline()
print(line)
# --> I'm expecting to see the new line, but this does not print anything!
這是行為標準嗎?我錯過了什么嗎?
注意:我知道有更好的方法來處理更新的檔案,例如使用這里指出的生成器:從經常更新的檔案中讀取。我只是想了解這個精確用例的問題。
uj5u.com熱心網友回復:
對于您的特定用例,解釋是 Vim 使用寫入臨時策略。這意味著所有寫入操作都在臨時檔案上執行。
相反,您的腳本從原始檔案中讀取,因此它看不到任何更改。
為了進一步測驗,您可以嘗試使用以下命令直接在檔案上寫入,而不是 Vim:
echo "Hello World" >> myfile.log
您應該會看到來自 python 的新行。
uj5u.com熱心網友回復:
要跟蹤您的檔案,您可以使用以下代碼:
f = open('myfile.log')
while True:
line = readline()
if not line:
print(line)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/330971.html
標籤:Python 蟒蛇-3.x 文件 python-3.6 阅读线
上一篇:為什么我不能轉換我在拆分存檔中收到的某些TIF檔案?
下一篇:對二進制字串的操作
