Renaming file extension using pathlib (python 3)

You have to actually rename the file not just print out the new name.

  1. Use Path.rename()

     from pathlib import Path
     my_file = Path("E:\\seaborn_plot\\x.dwt")
     my_file.rename(my_file.with_suffix('.txt'))
    

Note: To replace the target if it exists use Path.replace()

  1. Use os.rename()

     import os
     my_file="E:\\seaborn_plot\\x.dwt"
     new_ext=".txt"
     # Gets my_file minus the extension
     name_without_ext = os.path.splitext(my_file)[0]
     os.rename(my_file, name_without_ext + new_ext)
    

Ref:

  1. os.path.splitext(path)
  2. PurePath.with_suffix(suffix)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)