How to rename a file extension in Python


Task: there is a file with the .raw extension in the folder and I need to rename this file to the same one, but with a different .txt extension – how can I do this?

Solution:
You need to import the os module, which has the os.path.splitext() and os.rename() methods. Using the os.path.splitext() method, you can split the source file into two parts – its name and permission, which falls into square brackets as [0] – name and [1] – permission. Next, you just need to glue the name with the new permission via os.rename().

#Переименовать файл из .raw в .txt
import os
file="C:/Users/Vasya/Documents/Python/tangaria/scores.raw"
filename = os.path.splitext(file)[0]
os.rename(file, filename + ".txt")

 


This entry was posted in Python (en). Bookmark the permalink.

Leave a Reply

🇬🇧 Attention! Comments with URLs/email are not allowed.
🇷🇺 Комментарии со ссылками/email удаляются автоматически.