Python: Convert contents of a file to Uppercase characters only

后端 未结 3 795
盖世英雄少女心
盖世英雄少女心 2021-01-22 02:28

I am trying to convert the contents a set of files to only uppercase characters. Heres the code I have so far:

import os

def test():
    os.chdir(\"C:/Users/Dav         


        
3条回答
  •  长情又很酷
    2021-01-22 02:59

    You aren't actually writing the contents of the file. Try outputFile.write(content.upper()).

    import os
    
    def test():
        os.chdir("C:/Users/David/Files")
        files = os.listdir(".")
        for x in files:
            inputFile = open(x, "r")
            content = inputFile.read()
            with open(x, "wb") as outputFile:
                    outputFile.write(content.upper())
    

    When you open a file with w, any existing file with that name gets erased (see here). While this is fine, it is your statement str.upper(content) that is causing an issue because it doesn't actually do anything to the file - it uppercases content but doesn't write it anywhere (note you can also call .upper() on the content itself if you want). In order to write the contents to the file, you take the outputFile that you created and write content to it using the write() method. You can also use another with statement as you did when writing the file, which will ensure that it also gets properly closed:

    import os
    
    def test():
        os.chdir("C:/Users/David/Files")
        files = os.listdir(".")
        for x in files:
            with open(x, "r") as inputFile:
                content = inputFile.read()
            with open(x, "wb") as outputFile:
                outputFile.write(content.upper())
    

    You could also try opening the file in r+b mode, reading and then overwriting by seeking to the beginning of the file and writing (the file length should be the same, but you can use truncate() to clear the file after reading if need be):

    import os
    
    def test():
        x = 'testfile'
        with open(x, "r+b") as inputFile:
            content = inputFile.read()
            inputFile.seek(0)
            inputFile.write(content.upper())
    

提交回复
热议问题