I am trying to change the first character of each word in a list to upper case using Python 2.7. I am able to change the entire list to lower case, but I am not getting what I want - i.e the first character of each word to be upper case. Any help is appreciated.

Thank you

with open('c:\FLOUpper.txt', 'r') as infile,open('c:\FLOLower.txt', 'w') as outfile:
    data = infile.readlines()
    data = data.capitalize()
    outfile.write(data)

When I use the above code, its throwing a "list" object has no attributes 'capitalize.'

with open('c:\FLOUpper.txt', 'r') as infile,open('c:\FLOLower.txt', 'w') as outfile:
    data = infile.read()
    data = data.capitalize()
    outfile.write(data)

The above code changes the first character of the entire file to upper and all the rest to lower.

Dani AI

Generated

Quick diagnosis and what's going on: hit two separate issues. Calling .capitalize() on the result of readlines() fails because readlines() returns a list (lists have no capitalize method). Calling .capitalize() on the full string from read() will uppercase only the very first character of the whole file and force the rest to lowercase — that explains the unwanted output you saw.

A simple, robust pattern is to process the file line-by-line and capitalize each word rather than the whole blob. The standard library function string.capwords() is handy for this (it splits on whitespace and capitalizes each word). Use a safe file opener (to handle encodings) and raw paths on Windows to avoid escape-character bugs:

import string, codecs

inpath = r'c:\FLOUpper.txt'
outpath = r'c:\FLOLower.txt'

with codecs.open(inpath, 'r', 'utf-8') as fin, codecs.open(outpath, 'w', 'utf-8') as fout:
    for line in fin:
        fout.write(string.capwords(line))

If you build a list of transformed lines, write it with fout.writelines(lines) or fout.write(''.join(lines))fout.write(list) will not work. That ties back to (good list-comprehension idea) and (line-by-line loop is memory-friendly). For more precise control (hyphenated names, O'Connor, preserving inner-case like "iPhone") prefer a small custom routine or a regex-based replacement as suggested by ; str.title() (noted by ) is convenient but has known edge cases.

Troubleshooting checklist: use raw strings or forward slashes for Windows paths, handle encoding with codecs/io.open, avoid loading huge files into memory, and pick the capitalization method (capwords, title, or a regex/custom function) that matches your expected name formats.

Recommended Answers

All 7 Replies

Maybe:

with open('c:\FLOUpper.txt', 'r') as infile,open('c:\FLOLower.txt', 'w') as outfile:
    data = infile.readlines()
    data = [i.capitalize() for i in data]
    outfile.write(data)
commented: Great starting point. Thank you! +0

Good suggestion rr, but I think that just capitalizes the first word of each line. Instead of readlines() you want readwords(), except that doesn't exist.

I think judicious use of split() is in order, and remember each line will end with \n so you'll want to be sure to delete that so it's not part of the word.

Something like this ...

fname_in = "names_nocaps.txt"

# write a test data file
data = '''\
frank
heidi
karl
'''
with open(fname_in, 'w') as fout:
    for name in data:
        fout.write(name)

fname_out = "names_caps.txt"

# read the file back in and write the modified data back out
with open(fname_in, 'r') as fin, open(fname_out, 'w') as fout:
    for name in fin:
        name = name.capitalize()
        fout.write(name)

''' resulting file "names_caps.txt" shown with an editor ...
Frank
Heidi
Karl

'''

Note: You are not writing or reading a list object. To do so, you need to use the pickle module.

There is also a solution with the re module

import re

def cap(match):
    return match.group(0).capitalize()

with open('c:\FLOUpper.txt', 'r') as infile, open('c:\FLOLower.txt', 'w') as outfile:
    s = infile.read()
    s = re.sub(r'\b[a-zA-Z]\w*', cap, s)
    outfile.write(s)
commented: Utilized this solution and it worked like a charm. Thank you! +0

I want to see many options like in this website: Case Changer

Here you go:

s = "happy Hello World!"

print(s)
print(s.capitalize())
print(" ".join(w.capitalize() for w in s.split()))
print(s.lower())
print(s.upper())
print(s.swapcase())

''' my result -->
happy Hello World!
Happy hello world!
Happy Hello World!
happy hello world!
HAPPY HELLO WORLD!
HAPPY hELLO wORLD!
'''

How about

>>> 'tony veijalainen'.title()
'Tony Veijalainen'
>>> 'book of shadows'.title()
'Book Of Shadows'
>>> 

Second one is not actually how it is done, but otherwise it is OK.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.