Assignment #07: a file writer class¶
Assignment #07-01: an HTML writer¶
HTML files have a relatively simple structure. Here is an example:
<!DOCTYPE html>
<html>
<head>
<title>Tab title</title>
</head>
<body>
<h1>A large title</h1>
<h2>A smaller title</h2>
<p>
A paragraph with more or less text. Rather less.
</p>
<img alt="Image not found" src="/path/to/some/image.png">
<h2>Another smaller title</h2>
<p>
Another paragraph with more or less text. It depends on your mood.
</p>
</body>
</html>
Your task is to write an HTMLFile
class, which will help you to write such files in python. At instantiation, the HTMLFile
class must accept a positional and a keyword argument:
the positional argument
file_path
: a path to a file which will be created or overwritten by the object. The path must be ending with.html
, otherwise the__init__
method should raise an error.the keyword argument
header_title
which defaults to'Tab title'
.
The class must define the following instance methods:
add_body_title
, which adds an html title in the file. The size of the title (h1, h2, …) must be specified with a keyword argument.add_paragraph
, which adds a paragraph to the file.add_image
, which adds an image command to the file.end_file
, which writes the closing lines of the file.display_html
, which opens the file in your browser.
The class should define a new property, n_lines
, which returns the number of lines of the html file.
For example, the following code should write the template above and print the total number of lines:
file = HTMLFile('my_template.html', header_title='Tab title')
file.add_body_title('A large title')
file.add_body_title('A smaller title', size=2)
file.add_paragraph('A paragraph with more or less text. Rather less.')
file.add_image('/path/to/some/image.png', alt='Image not found')
file.add_body_title('Another smaller title', size=2)
file.add_paragraph('Another paragraph with more or less text. It depends on your mood.')
file.end_file()
print(file.n_lines)
Tip: you can decide to open and close the text file at each function call (ideally by using a with
context manager). However, you can also decide to store the commands in an instance attribute (a string) and write the string all at once when the end_file()
method is called. It’s up to you, but the second method is easier for exercise #07-02!
Assignment #07-02 (optional): change the header¶
For some reason, your clients are not happy with the current software design and made a request: they would like to be able to change the header at wish, after the class instantiation. That is, the following code should work:
file = HTMLFile('my_template.html')
file.header_title = 'A new tab title'
Implement this new functionality to your class!