I am using windows 10 and winpython. I have a file with a .dwt extension (it is a text file). I want to change the extension of this file to .txt.
My code does not throw any errors, but it does not change the extension.
from pathlib import Path
filename = Path("E:\\seaborn_plot\\x.dwt")
print(filename)
filename_replace_ext = filename.with_suffix('.txt')
print(filename_replace_ext)
Expected results are printed out (as shown below) in winpython's ipython window output:
E:\seaborn_plot\x.dwt
E:\seaborn_plot\x.txt
But when I look for a file with a renamed extension, the extension has not been changed, only the original file exists. I suspect windows file permissions.
You have to actually rename the file not just print out the new name.
Use Path.rename()
from pathlib import Path
myFile = Path("E:\\seaborn_plot\\x.dwt")
myFile.rename(myFile.with_suffix('.txt'))
Note: To replace the target if it exists use Path.replace()
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: