In: Computer Science
(In python)
4. Write a function that involves two arguments, named changeTheCase(myFile, case), that takes, as arguments, the name of a file, myFile, and the case, which will either be “upper” or “lower”. If case is equal to “upper” the function will open the file, convert all characters on each line to upper case, write each line to a new file, named “upperCase.txt”, and return the string “Converted file to upper case.” If case is equal to “lower” the function will open the file, convert all characters on each line to lower case, write each line to a new file, named “lowerCase.txt”, and return the string “Converted file to lower case.” If case is any other value, the function returns the string “Invalid parameter.”
For example: >>> changeTheCase(“hello.txt”, “upper”) should open the file named hello.txt, convert each character in each line to upper case, write each converted line to a new file named upperCase.txt, close both files, and return the string “Converted file to upper case.”
As another example: >>> changeTheCase(“hello.txt”, “lower”) should open the file named hello.txt, convert each character in each line to lower case, write each converted line to a new file named lowerCase.txt, close both files, and return the string “Converted file to lower case.” As a final example: >>> changeTheCase(“hello.txt”, “yibbie”) should return the string “Invalid parameter.”
In this program, we have to convert the contents of given file to either lowercase or uppercase.
To do that, first check the value of case parameter. If case is "upper" , then open myFile in read mode, read all the contents of the file using read() function. Convert the contents to upper case using upper() function, and finally write the converted content to upperCase.txt
Otherwise, if case is "lower", then follow the same process as above, but instead of converting the contents to upper case using upper() , convert the contents to lowercase using lower() function. And the converted contents are to written to 'lowerCase.txt'
program:
def changeTheCase(myFile, case):
if case=="upper":
f = open(myFile,'r')
data = f.read()
data = data.upper()
f2 = open('upperCase.txt','w')
f2.write(data)
f.close()
f2.close()
return "Converted file to upper case."
if case=="lower":
f = open(myFile,'r')
data = f.read()
data = data.lower()
f2 = open('lowerCase.txt','w')
f2.write(data)
f.close()
f2.close()
return "Converted file to lower case."
return "Invalid parameter"
I will use a sample file named input.txt to test this function. This is input.txt file:
sample function calls:
print(changeTheCase('input.txt','lower'))
print(changeTheCase('input.txt','upper'))
print(changeTheCase('input.txt','yibbe'))
outputs:
lowerCase.txt:
upperCase.txt: