Skip to content
The Chat Archive
llama-4-maverick-03-26-experimental· Meta LMArena Human Preference 140K

Write a function which tail a file from the end

  1. User

    Write a function which tail a file from the end

  2. Assistant

    Tail Function in Python

    Below is a Python function that mimics the behavior of the Unix tail command. It reads a file from the end and prints the last n lines. If n is not specified, it defaults to 10 lines.

    Code

    import os
    
    def tail_file(file_path, n=10):
        """
        Tails a file from the end and returns the last n lines.
    
        Args:
            file_path (str): Path to the file to be tailed.
            n (int, optional): Number of lines to return from the end. Defaults to 10.
    
        Returns:
            list: A list of the last n lines of the file.
        """
        try:
            with open(file_path, 'r') as file:
                # Get the file size
                file.seek(0, os.SEEK_END)
                file_size = file.tell()
                
                # Initialize variables
                block_size = 1024
                last_lines = []
                block = ''
                
                # Seek backwards from the end of the file
                while len(last_lines) < n and file_size > 0:
                    # Calculate the block end position
                    block_end = max(file_size - block_size, 0)
                    # Move the file pointer to the block start
                    file.seek(block_end)
                    # Read the block
                    new_block = file.read(file_size - block_end)
                    # Prepend the new block to the existing block
                    block = new_block + block
                    # Split the block into lines and add them to the list
                    last_lines = block.splitlines() + last_lines
                    # Adjust the file size for the next iteration
                    file_size = block_end
                    
                # Return the last n lines
                return last_lines[-n:]
        
        except FileNotFoundError:
            print(f"The file {file_path} does not exist.")
            return []
        except Exception as e:
            print(f"An error occurred: {e}")
            return []
    
    def main():
        file_path = 'example.log'  # replace with your file path
        n = 5  # number of lines to tail
        
        lines = tail_file(file_path, n)
        for i, line in enumerate(lines, 1):
            print(f"{i}: {line}")
    
    if __name__ == "__main__":
        main()
    

    Explanation

    1. The tail_file function opens the specified file in read mode.
    2. It seeks to the end of the file to determine its size (file_size).
    3. It then reads the file in blocks from the end towards the beginning. Each block is prepended to the block variable.
    4. Once a block is read, it's split into lines (last_lines). This process continues until we have at least n lines or we've read the entire file.
    5. Finally, the function returns the last n lines. If an error occurs (e.g., file not found), it catches the exception, prints an error message, and returns an empty list.

    Usage

    1. Replace 'example.log' in the main function with the path to your file.
    2. Adjust n to specify how many lines you want to tail from the file's end.
    3. Run the script. It will print the last n lines of your file, numbered for clarity.

    Why This Approach?

    • Memory Efficiency: Reading the entire file into memory is inefficient for large files. This approach reads the file in manageable blocks.
    • Flexibility: You can easily adjust the block_size variable for performance tuning based on your system's capabilities and the typical size of the files you're working with.
    • Robustness: The function handles exceptions gracefully, providing useful feedback instead of crashing unexpectedly.

    This implementation should serve well for most use cases, offering a good balance between simplicity and performance. Happy coding!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.