Capitalize first character of each sentence of a text file using Python

Hello friends, in this tutorial, I will tell you how you can capitalise the first character of every sentence of a text file using Python. Before diving into the way I would recommend you to check out my tutorial on text file.

Capitalize first character of each sentence of a text file using Python

I have created a sample text file ‘Codespeedy.txt’ for illustration purposes:

we are software development & app development company.
we can turn your idea into digital reality.
we provide digital and tech solutions for businesses. 
our team is always committed to fulfill your requirements.
turns your idea into business.

At first, I had to open my text file. To do so, I have used the open() function which takes the mode and the file’s location as argument. As I want to capitalize every sentence’s first character, I should retrieve each sentence from the text file. To do this I have used the readlines() function, which returns me a list of all the sentences from the text file.

Code :

path = r'/C:/Desktop/Codespeedy.txt'
f = open(path, 'r')
s = f.readlines()

for sentence in s:
    string = senetnce.capitalize()
    print(string, end = "")

Now I have run for loop to iterate over the list of sentences, s. For every sentence, I have used the capitalize() function. This function returns the input string by capitalizing the first character of the sentence. You can then print this sentence or write to a text file.

Output : 

We are software development & app development company.
We can turn your idea into digital reality.
We provide digital and tech solutions for businesses. 
Our team is always committed to fulfill your requirements.
Turns your idea into business.

Now you can take any string or contents of a text file and capitalize the first character of the sentence using the capitalize() function.

You can also check our tutorial on :

Leave a Reply

Your email address will not be published. Required fields are marked *