Objective
Develop a Python program that mimics the behavior of the Unix "more" command. This program should display the contents of a text file in chunks, pausing after every 24 lines and asking the user to press Enter to continue. Each line should be truncated to 79 characters for better readability.
The program should:
- Open a text file and read its content.
- Display up to 24 lines at a time, cutting off each line at 79 characters.
- Pause and wait for the user to press Enter before displaying the next chunk of lines.
- Repeat the process until the entire file is displayed.
This will help simulate the functionality of the "more" command in Unix-like systems.
Example Python Exercise
Show Python Code
def more_like_unix(file_name):
"""
Mimics the behavior of the Unix 'more' command.
Displays the contents of a text file in chunks of 24 lines, truncating each line to 79 characters.
Pauses after each chunk, waiting for the user to press Enter to continue.
Parameters:
file_name (str): The name of the file to display.
"""
try:
# Open the file in read mode
with open(file_name, 'r') as file:
# Read all lines from the file
lines = file.readlines()
# Process the lines in chunks of 24
total_lines = len(lines)
chunk_size = 24
for i in range(0, total_lines, chunk_size):
# Take a chunk of 24 lines
chunk = lines[i:i + chunk_size]
# Truncate each line to 79 characters
truncated_chunk = [line[:79] for line in chunk]
# Print the chunk of lines
for line in truncated_chunk:
print(line)
# If there are more lines to display, prompt user to continue
if i + chunk_size < total_lines:
input("\nPress Enter to continue...")
else:
print("\nEnd of file reached.")
break
except FileNotFoundError:
print(f"The file '{file_name}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage
if __name__ == "__main__":
file_name = input("Enter the file name to display: ")
more_like_unix(file_name)
Output
Enter the file name to display: example.txt
Line 1: This is a sample line of text that might be truncated if it's too long.
Line 2: Another line of text that will be truncated at 79 characters.
Line 3: This is a third line, also truncated to fit within the width.
...
Line 24: The 24th line of the current chunk.
Press Enter to continue...
Share this Python Exercise