'How to create an extension for a file without extension in Python

I have a folder with a list of files without extensions, I need to rename or create an extension to each file ".text"

This is my code, but there is a small bug, the second time I run the code the files renamed again with a long name ,, for example

The file name : XXA

after first run : XXA.text

second : XXAXXA.text.text

import os
def renamefiles():
  filelist = os.listdir(r"D:\")
  print(filelist)
  os.chdir(r"D:\")
  path = os.getcwd()

for filename in filelist:
   print("Old Name - "+filename)
   (prefix, sep, sffix) = filename.rpartition(".")
   newfile = prefix + filename + '.text'
   os.rename(filename, newfile)
   print("New Name - "+newfile)
   os.chdir(path)     
   rename_files()


Solution 1:[1]

Where you have

newfile = prefix + '.text'

You can have

if not file_name.contains(".text"):
    newfile = prefix + file_name + '.text'

Note where you have newfile = prefix + file_name + '.text', I changed it to newfile = prefix + '.text'. If you think about it, you don't need filename when you have already extracted the actual file name into prefix.

Solution 2:[2]

 for file in os.listdir(os.curdir):
     name, ext = os.path.splitext(file)
     os.rename(file, name + ".text")

Solution 3:[3]

Don't do the partitioning that way, use os.path.splitext:

file_name, extension = os.path.splitext(filename)
if not extension:
    newfile = file_name + '.text'
    os.rename(filename, newfile)

If the file has no extension splitext returns '' which is Falsy. The file extension can then be changed.

Solution 4:[4]

import os
def renamefiles():
  filelist = os.listdir(r"D:\")
  print(filelist)
  os.chdir(r"D:\")
  path = os.getcwd()

for filename in filelist:
   print("Old Name - "+filename)
   (prefix, sep, sffix) = filename.rpartition(".")
   newfile = prefix + filename + '.text'
   if not filename.endswith(".text"):
       os.rename(filename, newfile)
       print("New Name - "+newfile)
       os.chdir(path)     
       renamefiles()

You need to check if the filename ends with .text, and skip those

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3
Solution 4 Singh