Write a function which tail a file from the end
- User
Write a function which tail a file from the end
Assistant
Here's a Python function that tails a file from the end, similar to the Unix
tailcommand:def tail_file(filename, num_lines=10): """ Read the last n lines from a file. Args: filename (str): Path to the file to tail num_lines (int): Number of lines to return from the end (default: 10) Returns: list: List of the last n lines from the file """ try: with open(filename, 'rb') as file: # Go to the end of the file file.seek(0, 2) file_size = file.tell() # If file is empty, return empty list if file_size == 0: return [] lines = [] buffer = bytearray() position = file_size # Read backwards from the end while len(lines) < num_lines and position > 0: # Read in chunks for efficiency chunk_size = min(1024, position) position -= chunk_size file.seek(position) chunk = file.read(chunk_size) # Prepend to buffer buffer = chunk + buffer # Split into lines and process lines_in_buffer = buffer.split(b'\n') # Keep the incomplete line at the beginning for next iteration buffer = lines_in_buffer[0] # Add complete lines to our result (in reverse order) for line in reversed(lines_in_buffer[1:]): if line or len(lines) == 0: # Include empty lines except at very end lines.insert(0, line.decode('utf-8', errors='replace')) if len(lines) >= num_lines: break # Handle any remaining content in buffer if position == 0 and buffer: lines.insert(0, buffer.decode('utf-8', errors='replace')) # Return only the requested number of lines return lines[-num_lines:] except FileNotFoundError: print(f"Error: File '{filename}' not found") return [] except PermissionError: print(f"Error: Permission denied to read '{filename}'") return [] except Exception as e: print(f"Error reading file: {e}") return [] # Example usage if __name__ == "__main__": # Tail last 10 lines lines = tail_file("example.txt") for line in lines: print(line) # Tail last 5 lines lines = tail_file("example.txt", 5) for line in lines: print(line)For a simpler version that works well with smaller files:
def simple_tail(filename, num_lines=10): """ Simple tail function for smaller files. """ try: with open(filename, 'r') as file: lines = file.readlines() return [line.rstrip('\n') for line in lines[-num_lines:]] except Exception as e: print(f"Error: {e}") return []The first version is more memory-efficient for large files since it reads backwards in chunks rather than loading the entire file into memory. The second version is simpler but loads the whole file, which is fine for smaller files.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.