[英]Reading file continuously and appending new lines to list (python)
I am practicing file reading stuff in python.我正在 python 中练习文件阅读。 I got a text file and I want to run a program which continuously reads this text file and appends the newly written lines to a list.
我有一个文本文件,我想运行一个程序,它不断读取这个文本文件并将新写入的行附加到一个列表中。 To exit the program and print out the resulting list the user should press "enter".
要退出程序并打印出结果列表,用户应按“回车”。
The code I have written so far looks like this:到目前为止,我编写的代码如下所示:
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
So to break out of the while loop 'enter' should be pressed.所以要跳出while循环'enter'应该被按下。 To be fair I just copy pasted the solution to do this from here: Exiting while loop by pressing enter without blocking.
公平地说,我只是从这里复制粘贴了解决方案: Exiting while loop by press enter without blocking。 How can I improve this method?
我该如何改进这种方法?
But this code just appends all lines to my list again and again.但是这段代码只是一次又一次地将所有行添加到我的列表中。 So, say my text files contains the lines:
所以,假设我的文本文件包含以下行:
1
2
3
So my list is going to look like data = [1,2,3,1,2,3,1,2,3...]
and have a certain lenght until I press enter.所以我的列表看起来像
data = [1,2,3,1,2,3,1,2,3...]
并且有一定的长度,直到我按下回车键。 When I add a line (eg 4
) it will go data = [1,2,3,1,2,3,1,2,3,1,2,3,4,1,2,3,4...]
.当我添加一行(例如
4
)时,它将 go data = [1,2,3,1,2,3,1,2,3,1,2,3,4,1,2,3,4...]
.
So I am looking for some kind of if statement
before my append
command so that only the newly written line get appended.所以我在我的
append
命令之前寻找某种if statement
,以便只附加新写入的行。 But I can't think of something easy.但我想不出容易的事。
I already got some tips, ie我已经得到了一些提示,即
At the moment, I can't think of a way on how to do this.目前,我想不出如何做到这一点。 I tried fiddling around with
enumerate(f)
and itertools.islice
but can't make it work.我尝试摆弄
enumerate(f)
和itertools.islice
但无法使其工作。 Would appreciate some help, as I have not yet adopted the way of how programmers think.希望得到一些帮助,因为我还没有采用程序员的思维方式。
Store the file position between iterations.在迭代之间存储文件 position 。 This allows to efficiently fast-forward the file when it is opened again:
这允许在文件再次打开时有效地快进文件:
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
I could get it to work on Windows.我可以让它在 Windows 上工作。 First of all, exiting the
while
-loop and continuous reading the file are two different questions.首先,退出
while
循环和继续读取文件是两个不同的问题。 I assume, that exiting the while
loop is not the main problem, and because your select.select()
statement doesn't work this way on Windows, I created an exit-while with a try-except
clause that triggers on Ctrl-c.我认为,退出
while
循环不是主要问题,并且因为您的select.select()
语句在 Windows 上无法以这种方式工作,所以我创建了一个 exit-while 并带有一个在 Ctrl-c 上触发的try-except
子句. (It's just one way of doing it). (这只是一种方法)。
The second part of your questions is how to continuously read the file.您问题的第二部分是如何连续读取文件。 Well, not by reopening it again and again within the
while
loop, open it before the while
loop.好吧,不是在
while
while
之前打开它。
Then, as soon as the file is being changed, either a valid or an invalid line is read.然后,一旦文件被更改,就会读取有效或无效的行。 I suppose this happens because the iteration over
f
may sometimes happen before the file was completely written (I'm not quite sure about that).我想这是因为
f
的迭代有时可能发生在文件完全写入之前(我不太确定)。 Anyway, it is easy to check the read line.无论如何,很容易检查读取行。 I used again a
try-except
clause for it which catches the error if int(line)
raises an error.我再次使用了一个
try-except
子句,如果int(line)
引发错误,它会捕获错误。
Code:代码:
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.