Convert all the capital letters in a .txt file to small letters in Python
In this tutorial, we will learn how to change the case of all characters present in a text file using Python. We will use Python methods Python upper() to change all characters to upper case, and Python lower() to change all characters to lower case.
To convert all the capital letters in a .txt file to small letters in Python, follow the below steps:
Create a sample file:
Create a sample text file with any content that contains uppercase letters. For example:
CODESPEEDY TECHNOLOGY PRIVATE LIMITED IS AN IT COMPANY THAT PROVIDES CODING SOLUTIONS ALONG WITH VARIOUS IT SERVICES LIKE WEB DEVELOPMENT, SOFTWARE DEVELOPMENT.
Save the script in Python:
Save the following script in a Python file named convert_to_lowercase.py :
def convert_to_lowercase(file_path): try: with open(file_path, 'r') as file: content = file.read() lower_content = content.lower() with open(file_path, 'w') as file: file.write(lower_content) print("File content converted to lowercase successfully.") except Exception as e: print(f"An error occurred: {e}") convert_to_lowercase(sample.txt)
Now you can run the script by opening your terminal or command prompt, going to the directory where you have saved the script and the text file and typing the following command:
python convert_to_lowercase.py
Expected Output:
Once the script is executed the contents of sample.txt files are converted to lowercase. The file content will look like this:
codespeedy technology private limited is an it company that provides coding solutions along with various it services like web development, software development.
Also, a confirmation message will be displayed to the terminal by the script:
File content converted to lowercase successfully.
Leave a Reply