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
Show 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