I am practicing file reading stuff in 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. To be fair I just copy pasted the solution to do this from here: Exiting while loop by pressing 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. When I add a line (e.g. 4
) it will 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. But I can't think of something easy.
I already got some tips, i.e.
- Continuously checking the file size and only reading the part between old and new size.
- Keeping track of line number and skipping to line that is not appended in next iteration.
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. Would appreciate some help, as I have not yet adopted the way of how programmers think.