Exercise
Text To HTML Converter
Objective
Develop a Python program that functions as a "Text to HTML converter". This program will read the contents of a given text file and generate an HTML file based on it. For example, if the text file contains:
Hello
It's Me
I finished
The output HTML file should have the same name as the source file but with a ".html" extension (replacing the ".txt" if applicable). The "title" tag in the HTML's "head" section should be populated with the name of the source file.
Example Python Exercise
Show Python Code
# This program converts a text file to an HTML file with the same name but with a ".html" extension.
def text_to_html(input_filename):
try:
# Read the contents of the text file
with open(input_filename, 'r') as file:
text_content = file.readlines()
# Generate the output HTML filename by replacing ".txt" with ".html"
output_filename = input_filename.replace(".txt", ".html")
# Open the output HTML file in write mode
with open(output_filename, 'w') as html_file:
# Write the HTML structure
html_file.write('\n')
html_file.write('\n')
html_file.write('\n')
html_file.write(f'\t{input_filename}\n') # Set title as the input file name
html_file.write('\n')
html_file.write('\n')
# Write each line from the text file as a paragraph in the HTML file
for line in text_content:
html_file.write(f'\t{line.strip()}
\n')
html_file.write('\n')
html_file.write('\n')
print(f"HTML file generated: {output_filename}")
except FileNotFoundError:
print("The specified file does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage
input_file = "example.txt" # Replace with your text file name
text_to_html(input_file)
Output
example.txt
Hello
It's Me
I finished
Share this Python Exercise