Search code examples
pythonif-statementfile-rename

Is there a function in OS library or another python library that checks what the file extension is


I want to check if a file has a certain extension and then rename it like this:

import os

file_name = "path to file"
rename = "renamed file"

if file_name_extension == ".png":
   os.rename(file_name, rename)

Solution

  • Qt offers a robust class of filepath tools, QFileInfo

    from Pyside2 import QtCore
    ext = QtCore.QFileInfo(full_filepath).suffix()
    
    

    see docs at :https://doc.qt.io/qt-5/qfileinfo.html (note Qt docs are in c++ but are quite comprehensible for this question)