[英]Reading file continuously and appending new lines to list (python)
我正在 python 中練習文件閱讀。 我有一個文本文件,我想運行一個程序,它不斷讀取這個文本文件並將新寫入的行附加到一個列表中。 要退出程序並打印出結果列表,用戶應按“回車”。
到目前為止,我編寫的代碼如下所示:
import sys, select, os
data = []
i = 0
while True:
os.system('cls' if os.name == 'nt' else 'clear')
with open('test.txt', 'r') as f:
for line in f:
data.append(int(line))
print(data)
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
line_ = input()
break
所以要跳出while循環'enter'應該被按下。 公平地說,我只是從這里復制粘貼了解決方案: Exiting while loop by press enter without blocking。 我該如何改進這種方法?
但是這段代碼只是一次又一次地將所有行添加到我的列表中。 所以,假設我的文本文件包含以下行:
1
2
3
所以我的列表看起來像data = [1,2,3,1,2,3,1,2,3...]
並且有一定的長度,直到我按下回車鍵。 當我添加一行(例如4
)時,它將 go data = [1,2,3,1,2,3,1,2,3,1,2,3,4,1,2,3,4...]
.
所以我在我的append
命令之前尋找某種if statement
,以便只附加新寫入的行。 但我想不出容易的事。
我已經得到了一些提示,即
目前,我想不出如何做到這一點。 我嘗試擺弄enumerate(f)
和itertools.islice
但無法使其工作。 希望得到一些幫助,因為我還沒有采用程序員的思維方式。
在迭代之間存儲文件 position 。 這允許在文件再次打開時有效地快進文件:
data = []
file_position = 0
while True:
with open('test.txt', 'r') as f:
f.seek(file_position) # fast forward beyond content read previously
for line in f:
data.append(int(line))
file_position = f.tell() # store position at which to resume
我可以讓它在 Windows 上工作。 首先,退出while
循環和繼續讀取文件是兩個不同的問題。 我認為,退出while
循環不是主要問題,並且因為您的select.select()
語句在 Windows 上無法以這種方式工作,所以我創建了一個 exit-while 並帶有一個在 Ctrl-c 上觸發的try-except
子句. (這只是一種方法)。
您問題的第二部分是如何連續讀取文件。 好吧,不是在while
while
之前打開它。
然后,一旦文件被更改,就會讀取有效或無效的行。 我想這是因為f
的迭代有時可能發生在文件完全寫入之前(我不太確定)。 無論如何,很容易檢查讀取行。 我再次使用了一個try-except
子句,如果int(line)
引發錯誤,它會捕獲錯誤。
代碼:
import sys, select, os
data = []
with open('text.txt', 'r') as f:
try:
while True:
os.system('cls' if os.name == 'nt' else 'clear')
for line in f:
try:
data.append(int(line))
except:
pass
print(data)
except KeyboardInterrupt:
print('Quit loop')
print(data)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.