Search code examples
pythonoperating-systemfile-rename

I am trying to rename multiple files at a time using os.rename


I am trying to rename multiple files using os.rename in win8.1

import os

path = "C:\\Users\\Aniket\\Desktop\\Python projects\\p"
di = os.listdir(path)
os.chdir(path)
for file in di :
    i = 0
    file_name , file_ext = os.path.splitext(file)
    new_name = "file"+str(i)+f"{file_ext}"
    os.rename(new_name, file)
    i+=1

I want 6464.txt to be renamed file0.txt. But FileNotFoundError: system can't find the specified file: 'file0.txt'-> '6464.txt' appears. (file0 is new name while 6464 is existing name)


Solution

  • You have it the wrong way around. os.rename works os.rename(src, dst). So just switch os.rename(file, new_name)