jeudi 14 juillet 2016

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()

Aucun commentaire:

Enregistrer un commentaire