Search code examples
pythonarrayslistfile-handling

converting the last word of a file into uppercase and writing the new content into a new file in Python


Here is the code I tried! the content in text.txt file is

INPUT

file=open('text.txt','r')
file.seek(0)
a=file.read()
Lst = a.split()
print(Lst)
length=len(Lst)
print(Lst[length-1].upper())
Lst[length-1]).upper()
print(Lst)
#------------------------------#
newfile=open("newfile.txt","w")
newfile.writelines(Lst)
newfile.close()
file.close()

Output screenshot of the result as u can see the conversion of uppercase doesn't show up and the same output gets written in newfile,

Thanks!


Solution

  • upper() doesn't change the element of the list, it just returns the uppercased value. To change it you must assign to the element:

    Lst[length-1] = Lst[length-1].upper()