KrankenWagen
KrankenWagen

Reputation: 27

How can I manipulate a txt file to be all in lowercase in python?

Let's say that I have a txt file that I have to get all in lowercase. I tried this

def lowercase_txt(file):
     file = file.casefold()
     with open(file, encoding = "utf8") as f:
         f.read()

Here I get "'str' object has no attribute 'read'"

then I tried

def lowercase_txt(file):
    with open(poem_filename, encoding="utf8") as f:
         f = f.casefold()
         f.read()

and here '_io.TextIOWrapper' object has no attribute 'casefold'

What can I do?

EDIT: I re-runned this exact code and now there are no errors (dunno why) but the file doesn't change at all, all the letters stay the way they are.

Upvotes: 0

Views: 259

Answers (1)

Booboo
Booboo

Reputation: 44148

This will rewrite the file. Warning: if there is some type of error in the middle of processing (power failure, you spill coffee on your computer, etc.) you could lose your file. So, you might want to first make a backup of your file:

def lowercase_txt(file_name):
     """
     file_name is the full path to the file to be opened
     """
     with open(file_name, 'r', encoding = "utf8") as f:
         contents = f.read() # read contents of file
     contents = contents.lower() # convert to lower case
     with open(file_name, 'w', encoding = "utf8") as f: # open for output
         f.write(contents)

For example:

lowercase_txt('/mydirectory/test_file.txt')

Update

The following version opens the file for reading and writing. After the file is read, the file position is reset to the start of the file before the contents is rewritten. This might be a safer option.

def lowercase_txt(file_name):
    """
    file_name is the full path to the file to be opened
    """
    with open(file_name, 'r+', encoding = "utf8") as f:
        contents = f.read() # read contents of file
        contents = contents.lower() # convert to lower case
        f.seek(0, 0) # position back to start of file
        f.write(contents)
        f.truncate() # in case new encoded content is shorter than older

Upvotes: 1

Related Questions