Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming file extension using pathlib (python 3)

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.

like image 524
user3398600 Avatar asked Jan 11 '19 19:01

user3398600


People also ask

How do I rename a file in Pathlib?

Path.rename(target) Rename this file or directory to the given target. On Unix, if target exists and is a file, it will be replaced silently if the user has permission. target can be either a string or another path object.

What is the use of Pathlib in Python?

Fortunately, if you're coding in Python, the Pathlib module does the heavy lifting by letting you make sure that your file paths work the same in different operating systems. Also, it provides functionalities and operations to help you save time while handling and manipulating paths.

How do I rename a file in Shutil?

You can rename a directory in Python by moving it using the shutil module. The shutil. move(src, dst) moves the directory from src to dst. If you just change the name of the directory without specifying the path, you'll basically be renaming it.


2 Answers

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)
like image 132
Bitto Bennichan Avatar answered Sep 17 '22 18:09

Bitto Bennichan


From the docs:

Path.rename(target)

Rename this file or directory to the given target. On Unix, if target exists and is a file, it will be replaced silently if the user has permission. target can be either a string or another path object.

pathlib — Object-oriented filesystem paths on docs.python.org

You could use it like this:

from pathlib import Path   filename = Path("E:\\seaborn_plot\\x.dwt") filename_replace_ext = filename.with_suffix(".txt") filename.rename(filename_replace_ext) 
like image 26
alejandro joya cruz Avatar answered Sep 16 '22 18:09

alejandro joya cruz