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

前端 未结 5 1776
故里飘歌
故里飘歌 2020-12-17 03:40

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

相关标签:
5条回答
  • 2020-12-17 03:43

    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.

    0 讨论(0)
  • 2020-12-17 03:45

    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']
    
    0 讨论(0)
  • 2020-12-17 03:57

    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)
    
    0 讨论(0)
  • 2020-12-17 04:08

    A possible solution:

    lines = [ l for l in open("Output.txt")]
    file = open('Output.txt', 'w')
    file.write(lines[-3:0])
    file.close()
    
    0 讨论(0)
  • 2020-12-17 04:09

    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))
    
    0 讨论(0)
提交回复
热议问题