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 word in a text file entered by the user at runtime.

Things to do Before the 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 in a file entered by the user get capitalized. Capitalizing means that the first letter of a word becomes a capital letter.

Therefore, first create a file named codescracker.txt with the 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 a snapshot of the opened file, codescracker.txt:

python capitalize each word in file

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

Capitalize each word in the file

This Python receives the name of the file from the 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 the file, say, codescracker.txt, and press the ENTER key to capitalize the 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 codescracker.txt after executing the above program:

python capitalize words in file

Note: The title() method converts the first letter of each word into a capital letter or uppercase.

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

The program works in such a way that the file is opened in reading mode, and all of its content gets read. All words get capitalized and initialized to the totContent variable. Now the file gets closed using the 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 the words in a file.

Modified version of the previous program

This program is a modified version of the previous program. This program includes error handling code while operating with files. That is, it handles the error when the file entered by the 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 codescracker.txt (an existing file):

capitalize all words in file python

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

python capitalize first letter of all words in file

Python Online Test


« Previous Program Next Program »


Liked this post? Share it!