Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy the last three lines of a text file in python?

Tags:

python

text

list

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()
like image 686
Zac Avatar asked Mar 26 '13 21:03

Zac


2 Answers

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))
like image 197
Jon Clements Avatar answered Oct 06 '22 21:10

Jon Clements


As long as you're ok to hold all of the file lines in memory, you can slice the list of lines to get the last x items. See http://docs.python.org/2/tutorial/introduction.html and search for 'slice notation'.

def get_chat_lines(file_path, num_chat_lines):
    with open(file_path) as src:
        lines = src.readlines()
        return lines[-num_chat_lines:]


>>> lines = get_chat_lines('Output.txt', 3)
>>> print(lines)
... ['line n-3\n', 'line n-2\n', 'line n-1']
like image 24
Rob Cowie Avatar answered Oct 06 '22 22:10

Rob Cowie