How to change file extension in Python?

PythonServer Side ProgrammingProgramming

When changing the extension, you're basically just renaming the file and changing the extension. In order to do that, you need to split the filename by '.' and replace the last entry by the new extension you want. You can do this using the os.rename method. 


>>> import os
>>> my_file = 'my_file.txt'
>>> base = os.path.splitext(my_file)[0]
>>> os.rename(my_file, base + '.bin')

This will rename my_file.txt to my_file.bin

Updated on 18-Feb-2020 06:07:53