Show File Data - Python Programming Exercise

In this exercise, you will develop a Python program to read and display the contents of a text file. This exercise is perfect for practicing file handling, command-line arguments, and user input in Python. By implementing this program, you will gain hands-on experience in handling file operations, command-line arguments, 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

Show File Data

 Objective

Develop a Python program to read and display the contents of a text file. If a file name is provided through the command line, use it directly. Otherwise, prompt the user to input the file name. Ensure to read the file using a suitable method, such as opening it in read mode, and display its contents line by line on the screen.

 Example Python Exercise

 Copy Python Code
import sys

def read_and_display_file():
    """
    Reads and displays the contents of a text file. If no filename is provided via the command line,
    prompts the user to enter one. The file is opened in read mode and its contents are printed line by line.
    """
    # Check if the file name is provided as a command-line argument
    if len(sys.argv) > 1:
        file_name = sys.argv[1]
    else:
        # If no command-line argument, prompt the user for the file name
        file_name = input("Enter the file name: ")

    try:
        # Open the file in read mode and display its contents line by line
        with open(file_name, 'r') as file:
            print(f"\nContents of '{file_name}':\n")
            for line in file:
                print(line, end='')  # `end=''` avoids adding extra newlines
    except FileNotFoundError:
        print(f"Error: The file '{file_name}' was not found.")
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    read_and_display_file()

 Output

python program.py example.txt
Contents of 'example.txt':

This is the first line.
This is the second line.
This is the third line.

 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.

  •  TextToHTML with File Integration

    In this exercise, you will develop a Python program to enhance the TextToHTML class by adding the ability to save its results into a text file. This exercise i...

  •  Log Handler

    In this exercise, you will develop a Python program with a class called Logger, which includes a static method called log. This exercise is perfect for practic...

  •  More

    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,...

  •  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 ...