我想閱讀添加到檔案中的最新行
myfile = open("Username.txt", "r")
lines = myfile.readline()
GetTopic = print lines(recent line)
if GetTopic == "....":
then ......
uj5u.com熱心網友回復:
檔案不保存更改歷史記錄。作業系統可能會存盤檔案最后一次更改的時間,但沒有像“最近添加的行”這樣的東西。
因此,你想做的事情是不可能的。
編輯:如果您指的是檔案的最后一行,那么您就是這樣做的。
myfile = open("Username.txt", "r")
lines = myfile.readlines()
print(lines[-1])
將回傳檔案的最后一行。
編輯2:
如果檔案非常大并且不適合記憶體:
myfile = open("Username.txt", "r")
last_line = ""
for line in myfile:
last_line = line
print(last_line) # Will hold last line in the file
uj5u.com熱心網友回復:
正如@0xRyN 提到的,如果要在檔案更新時更新行,則必須處理作業系統級別的代碼。但是,如果您只想在打開檔案后立即使用最后一行,則可以使用它
....
Lines = file1.readlines()
lastLine = Lines[-1]
print(lastLine)
uj5u.com熱心網友回復:
with open("test.txt","r") as file:
lines = file.readlines()
print(lines[-1])
uj5u.com熱心網友回復:
三種方式:
使用回圈:
with open(ur_file) as f:
for line in f:
pass
# end of the with block, line will be the last line
使用具有合理最大值的雙端佇列并取最后一個:
def tail(filename, n=10):
'Return the last n lines of a file'
with open(filename) as f:
return deque(f, n)
對于 HUGE 檔案,您可能想要搜索到最后,倒帶一點,然后閱讀以下行:
offset=2000 #size known to contain a line break
with open(ur_file) as f:
f.seek(0, 2)
end=f.tell()
f.seek(end-offset)
last=f.readlines()[-1]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/458905.html
標籤:Python python-3.x 文件 外部的 写作
