Python Program to Capitalize each Word in a File

In this article, you will learn and get code in Python, to capitalize each and every (all) words in a text file entered by user at run-time.

Things to do Before Program

Because the program given below is used to capitalize each word in a File. That is, after executing the program given below, all words of a file entered by user gets capitalized. Capitalize means, the first letter of a word becomes capital letter.

Therefore, first create a file named fresherearth.txt with following content:

hello python
this is a file

Save this file inside the current directory, the directory where the python program to capitalize each word in a file is saved. Here is the snapshot of the opened file, fresherearth.txt:

python capitalize each word in file

Now let's create a Python program to capitalize all words of this file.

Capitalize Each Word in File

This Python receives the name of file from user at run-time and capitalizes all of its words. The question is, write a Python program to capitalize each word in a file. Here is its answer:

totContent = ""
print("Enter the Name of File: ")
fileName = str(input())
fileHandle = open(fileName, "r")

for content in fileHandle:
    newContent = content.title()
    totContent = totContent + newContent

fileHandle.close()
fileHandle = open(fileName, "w")
fileHandle.write(totContent)

print("All Words Capitalized Successfully!")
fileHandle.close()

Here is its sample run:

capitalize first letter of every word in file python

Now enter the name of file say fresherearth.txt and press ENTER key to capitalize first letter of every word in this file. Here is the sample run:

python capitalize all words in file

And here is the opened file fresherearth.txt after executing the above program:

python capitalize words in file

Note - The title() method converts first letter of each word in capital letter or uppercase.

Note - To capitalize each word without using title(), refer to capitalize each word in string article to implement the code manually.

The program works in a way that, the file is opened in reading mode and all of its content gets read. All words gets capitalized and initialized to totContent variable. Now file gets closed using close() method. The file again gets opened, but in writing mode this time, to put the content of totContent in the same file. In this way, we've capitalized all words in a file.

Modified Version of Previous Program

This program is the modified version of previous program. This program includes error handling code while operating with files. That is, it handles the error when the file entered by user doesn't exist in the directory. Let's have a look at the program:

totContent = ""
print(end="Enter the Name of File: ")
fileName = str(input())

try:
    fileHandle = open(fileName, "r")
    for content in fileHandle:
        newContent = content.title()
        totContent = totContent + newContent
    fileHandle.close()
	
    try:
        fileHandle = open(fileName, "w")
        fileHandle.write(totContent)
        print("\nAll Words in \"" + fileName + "\" Capitalized Successfully!")
        print(end="\nWant to see the Content of File (y/n): ")
        ch = input()
        if ch=='y':
            fileHandle = open(fileName, "r")
            for content in fileHandle:
                print(end=content)
        else:
            print("Exiting...")
        fileHandle.close()
        print()
    except IOError:
        print("Error Occurred!")
		
except IOError:
    print("\nThe \"" + fileName + "\" is not Exist!")
    print("Exiting...")

Here is its sample run with user input say fresherearth.txt (existing file):

capitalize all words in file python

And here is another sample run with user input say codes.txt (non-existing file):

python capitalize first letter of all words in file

Python Online Test


« Previous Program Next Program »