1

I am creating a GUI for the program that renames all the files numerically (eg. 1, 2, 3, etc) in python 3.10, Visual Studio 2022. I am receiving this error on os.rename() in the for loop -

[WinError 17] The system cannot move the file to a different disk

Here's my whole code -

from tkinter import *
import tkinter.filedialog
import os
import pathlib

window=Tk()
window.title('Hello Python')
window.geometry("300x200+10+10")
window.resizable(False, False)
window.configure(bg='white')

brackets = False

def rename():
    fileNumber = 1
    folderPath = tkinter.filedialog.askdirectory(parent=window, initialdir='Documents', title='Please select a folder')
    for filename in os.listdir(folderPath):
        fileExt = pathlib.Path(filename).suffix
        filePath = folderPath + '/' + filename
        if (fileExt != '.py') :
            if (brackets):
                os.rename(filePath, str(fileNumber) + ')' + fileExt)
            else:
                os.rename(filePath, str(fileNumber) + fileExt)
            fileNumber += 1

lbl=Label(window, text="Welcome to rename it!", fg='black', bg='white', font=("Helvetica", 20))
lbl.place(relx = 0.5, y = 25, anchor=CENTER)

btn=Button(window, text="Rename", fg='blue', command=rename)
btn.place(x=80, y=100)

window.mainloop()

I don't want to move the files, I just want to rename them. Any help would be appreciated.

Ninad Kulkarni
  • 61
  • 1
  • 11

2 Answers2

0

based on: https://stackoverflow.com/a/21116654/14681307

os.rename can't move data. It only renames files. in this way, your can't rename a file to another drive.

Moving between drives is copying it first, and then deleting the source file. you can use the shutil.move() method which does it when you trying to transfer files between two drives

import shutil
shutil.move(src,dest)

Of course, in this case, you do not move files between the drivers, but using shutil may help you

Ninad Kulkarni
  • 61
  • 1
  • 11
mmdbalkhi
  • 29
  • 1
  • 9
0

I was doing trial and error on this code to find the solution, and this was the problem -

os.rename(filePath, str(fileNumber) + fileExt)

Suppose this is the path - D:\file.png and I want to rename it to D:\1.png. In the os.rename command I renamed D:\file.png to 1.png. I forgot the path behind the file, which, in this case, was D:\. So the os.rename command needs to be like this -

os.rename(filePath, os.path.dirname(filePath) + "//" + str(fileNumber) + fileExt)
Ninad Kulkarni
  • 61
  • 1
  • 11