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 seek
ing 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())