logo CodeStepByStep logo

print_box

Language/Type: Python file input

Write a function named print_box that accepts two parameters: a string holding a file name, and an integer for a width. Your function should open that file and reads its contents as a sequence of lines, and display the lines to the console with a 'box' border of # characters around them on all four sides. The second parameter to your function indicates the total width of the box including its border. You must also convert each line to "title case" by capitalizing the first letter of the line and lowercasing all subsequent letters. For example, suppose the file poem.txt contains the following text:

roses ARE red
VIOLETS Are bl_u_e

All my BASE
ARE belong To YOU

Then the following calls would produce the following console output. If any lines in the file are too long to fit into the box, truncate them.

print_box("poem.txt", 19) print_box("poem.txt", 30) print_box("poem.txt", 7)
###################
#Roses are red    #
#Violets are blue #
#                 #
#All my base      #
#Are belong to you#
###################
##############################
#Roses are red               #
#Violets are blue            #
#                            #
#All my base                 #
#Are belong to you           #
##############################
#######
#Roses#
#Viole#
#     #
#All m#
#Are b#
#######

You may assume that the input file exists and is readable, and that its lines can fit within the given width. You may assume that the width value passed will be at least 2. Notice that the file might contain blank lines. Your solution should read the file only once, not make multiple passes over the file data.

Function: Write a Python function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.