More - Python Programming Exercise

In this exercise, you will develop a Python program that mimics the behavior of the Unix "more" command. This exercise is perfect for practicing file handling, loops, and user input in Python. By implementing this program, you will gain hands-on experience in handling file operations, loops, and user input in Python. This exercise not only reinforces your understanding of file handling but also helps you develop efficient coding practices for managing user interactions.

 Category

Managing Files

 Exercise

More

 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

 Copy 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

 More Python Programming Exercises of Managing Files

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  Text Modifier

    In this exercise, you will develop a Python program that reads a text file, replaces specified words, and saves the modified content into a new file. This exercise...

  •  Count characters in a text file

    In this exercise, you will develop a Python program that counts how many times a specific character appears in a given file (of any type). This exercise is per...

  •  Binary File Reading (BMP Example)

    In this exercise, you will develop a Python program that verifies if a BMP image file is valid by checking its header. This exercise is perfect for practicing ...

  •  Saving Data to a Binary File

    In this exercise, you will develop a Python program that prompts the user to enter their name, age (as a byte), and birth year (as an integer), then saves this inform...

  •  Reverse the contents of a text file

    In this exercise, you will develop a Python program that inverts the contents of a text file. This exercise is perfect for practicing file handling, loops, and...

  •  Working with binary GIF files

    In this exercise, you will develop a Python program to validate the structure of a GIF image file. This exercise is perfect for practicing file handling, byte ...