Copy the last three lines of a text file in python?
list, python, text
Solution
To get the last three lines of a file efficiently, use `deque`:
from collections import deque
with open('somefile') as fin:
last3 = deque(fin, 3)
This saves reading the whole file into memory to slice off what you didn't actually want.
To reflect your comment - your complete code would be:
from collections import deque
with open('somefile') as fin, open('outputfile', 'w') as fout:
fout.writelines(deque(fin, 3))
Problem
I'm new to python and the way it handles variables and arrays of variables in lists is quite alien to me. I would normally read a text file into a vector and then copy the last three into a new array/vector by determining the size of the vector and then looping with a for loop a copy function for the last size-three into a new array. I don't understand how for loops work in python so I can't do that. so far I have: ``` #read text file into line list numberOfLinesInChat = 3 text_file = open("Output.txt", "r") lines = text_file.readlines() text_file.close() writeLines = [] if len(lines) > numberOfLinesInChat: i = 0 while ((numberOfLinesInChat-i) >= 0): writeLine[i] = lines[(len(lines)-(numberOfLinesInChat-i))] i+= 1 #write what people say to text file text_file = open("Output.txt", "w") text_file.write(writeLines) text_file.close() ```