This is a Python Program to read a file and capitalize the first letter of every word in the file.
This is a Python Program to read a file and capitalize the first letter of every word in the file.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Problem Description
The program reads a file and capitalizes the first letter of every word in the file.
Problem Solution
1. Take the file name from the user.
2. Read each line from the file and use the title() function to capitalize each word in the
line.
3. Print the altered lines of the file.
5. Exit.
Program/Source Code
Here is source code of the Python Program that reads a file and capitalizes the first letter
of every word in the file. The program output is also shown below.
fname = input(“Enter file name: “)
with open(fname, ‘r’) as f:
for line in f:
l=line.title()
print(l)
Program Explanation
1. User must enter a file name.
2. The file is opened using the open() function in the read mode.
3. A for loop is used to read through each line in the file.
4. Each word in the line is capitalized using the title() function.
5. The altered lines are printed.
Runtime Test Cases
Case 1:
Contents of file:
hello world
hello
Output:
Enter file name: read.txt
Hello World
Hello
Case 2:
Contents of file:
test1 test2
Output:
Enter file name: read2.txt
Test1 Test2