Exercise
Transform A Text File To Uppercase
Objective
Develop a Python program that reads the contents of a text file and writes it to a new file, converting all lowercase letters to uppercase.
Example Python Exercise
Show Python Code
# Define a function to convert the text to uppercase and write to a new file
def convert_to_uppercase(input_filename, output_filename):
try:
# Open the input file in read mode
with open(input_filename, 'r') as infile:
# Read the contents of the file
content = infile.read()
# Convert the content to uppercase
content_uppercase = content.upper()
# Open the output file in write mode
with open(output_filename, 'w') as outfile:
# Write the uppercase content to the new file
outfile.write(content_uppercase)
print("File has been successfully converted to uppercase and saved as", output_filename)
except FileNotFoundError:
print(f"The file {input_filename} does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
# Call the function with the input and output file names
input_file = "example.txt" # Example input file
output_file = "example_uppercase.txt" # Output file for the uppercase content
convert_to_uppercase(input_file, output_file)
Output
If the example.txt file contains:
Hello world!
This is a test.
After running the program, the content of example_uppercase.txt will be:
HELLO WORLD!
THIS IS A TEST.
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.
In this exercise, you will develop a Python program that reads any file and transfers its content to another file, converting all lowercase letters to uppercase. This...
In this exercise, you will develop a Python program to "invert" a file. This exercise is perfect for practicing file handling, byte manipulation, and loops in ...
In this exercise, you will develop a Python program to encode the content of a text file into a new file, transforming the text in a way that it is not easily readabl...
In this exercise, you will develop a Python program to count the total number of words in a given text file. This exercise is perfect for practicing file handl...
In this exercise, you will develop a Python program to read the dimensions (width and height) of a BMP file using a BinaryReader-like approach. This exercise i...
In this exercise, you will develop a Python program that functions as a "Text to HTML converter". This exercise is perfect for practicing file handling, string...