How to Capitalize First Letter of Word in Python


In this example we will show how to read a file and capitalize the first letter of each word in the file.

2.  Codes

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

fileName = input("Enter file name")
content = []
with open(fileName, 'r') as file:
    lines = file.readlines()
    for line in lines:
        content.append(line.title())

with open(fileName, 'w') as file2:
    for line in content:
        file2.write(line)

The original content in test.txt:

Python is easy to learn.
It is one of the most popular programming language.

After capitalization, the content is changed to:

Python Is Easy To Learn.
It Is One Of The Most Popular Programming Language.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments