简体   繁体   中英

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

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()

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))

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']

First to answer your question, my guress is that you had an index error you should replace the line writeLine[i] with writeLine.append( ). After that, you should also do a loop to write the output :

text_file = open("Output.txt", "w")
for row in writeLine :
    text_file.write(row)
text_file.close()

May I suggest a more pythonic way to write this ? It would be as follow :

with open("Input.txt") as f_in, open("Output.txt", "w") as f_out :
    for row in f_in.readlines()[-3:] :
        f_out.write(row)

A possible solution:

lines = [ l for l in open("Output.txt")]
file = open('Output.txt', 'w')
file.write(lines[-3:0])
file.close()

This might be a little clearer if you do not know python syntax.

lst_lines = lines.split()

This will create a list containing all the lines in the text file.

Then for the last line you can do:

last = lst_lines[-1] secondLAst = lst_lines[-2] etc... list and string indexes can be reached from the end with the '-'.

or you can loop through them and print specific ones using:

start = start line, stop = where to end, step = what to increment by.

for i in range(start, stop-1, step): string = lst_lines[i]

then just write them to a file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM