Change case of all characters in a .txt file using Python
Last Updated :
16 Nov, 2022
In this article, 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.
For example, If we have text file data.txt as shown below.
Change all characters to uppercase from the text file
In this method, we will read line by line from the text file and change the case, and write that line to a new text file. We will read each line from this file, change the case and write it into an output.txt file.
Python3
with open ( 'data.txt' , 'r' ) as data_file:
with open ( 'output.txt' , 'a' ) as output_file:
for line in data_file:
output_file.write(line.upper())
|
Output:
Change all characters to lowercase from the text file
In this method, we will read the entire file, convert the case of all characters and write it into the new file. Here also we will take the same txt file data.txt and read the entire file and convert characters to lowercase using the lower() method and write to the output.txt file.
Python3
with open ( 'data.txt' , 'r' ) as data_file:
with open ( 'output.txt' , 'a' ) as output_file:
output_file.write(data_file.read().lower())
|
Output:
Capitalize the first letter of each word from the text file
The first letter of each word found in the text file will be capitalized in this manner. The input file will be the same data.txt file. We need an inbuilt technique to simply change the first letter to uppercase. Therefore, using a new function, we will loop through each word in the file and change the case of the word’s first letter.
Python3
def capitalize_first_letter(wrd):
return wrd[ 0 ].upper() + wrd[ 1 :].lower()
with open ( 'data.txt' , 'r' ) as data_file:
with open ( 'output.txt' , 'a' ) as output_file:
for line in data_file:
word_list = line.split()
word_list = [capitalize_first_letter(word) for word in word_list]
output_file.write( " " .join(word_list) + "\n" )
|
Output:
Please Login to comment...