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. 

example

>>> 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

raja
Published on 27-Dec-2017 11:19:36
Advertisements