llama-4-maverick-03-26-experimental· Meta LMArena Human Preference 140K
Write a function which tail a file from the end
- User
Write a function which tail a file from the end
- Assistant
Tail Function in Python
Below is a Python function that mimics the behavior of the Unix
tailcommand. It reads a file from the end and prints the lastnlines. Ifnis 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
- The
tail_filefunction opens the specified file in read mode. - It seeks to the end of the file to determine its size (
file_size). - It then reads the file in blocks from the end towards the beginning. Each block is prepended to the
blockvariable. - Once a block is read, it's split into lines (
last_lines). This process continues until we have at leastnlines or we've read the entire file. - Finally, the function returns the last
nlines. If an error occurs (e.g., file not found), it catches the exception, prints an error message, and returns an empty list.
Usage
- Replace
'example.log'in themainfunction with the path to your file. - Adjust
nto specify how many lines you want to tail from the file's end. - Run the script. It will print the last
nlines 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_sizevariable 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!
- The
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.