Sam Chan
Sam Chan

Reputation: 550

Python Rename() PermissionError: [WinError 32]?

I am trying to order all the files in a directory simply by adding numbers before their old file names(e.g "Oldfilename" should be named "1. Oldfilename").

import os
i=0
def OrderFile(x):
    ListOfFile=os.listdir(x)
    for file in  ListOfFile:
        global i
        filepath=os.path.join(x,file)
        file=str(i)+'. '+file
        newfilepath=os.path.join(filepath,file)
        i=i+1
        os.rename(filepath,newfilepath)

But I get an error:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 
'D:\\baiduyundownload\\Tempo\\Active\\Learning\\Sleep.PNG' ->     
'D:\\baiduyundownload\\Tempo\\Active\\Learning\\Sleep.PNG\\1.Sleep.PNG'
  1. I have searched for the documentation for rename(), but nothing is helpful.
  2. Also, I searched for a dozen of similar problem, and I know that the file that I am trying to rename must be opened before I execute the rename function.
  3. The only suspicious act that 's related to opening the file I can detect is the 'for' loop, but then I found the element the foor loop is giving me is of str type.
  4. Also I tried to rename the file above by manually setting the 'src' and 'dst', and it worked just fine. So the file itself has nothing to do with the error.
  5. So, then I got stuck.

Upvotes: 1

Views: 5838

Answers (1)

Munir
Munir

Reputation: 3612

filepath already contains the filename in it. You want to rename x\file not filepath\file

import os
i=0
def OrderFile(x):
    ListOfFile=os.listdir(x)
    for file in  ListOfFile:
        global i
        filepath=os.path.join(x,file)
        file=str(i)+'. '+file
        newfilepath=os.path.join(x,file)
        i=i+1
        os.rename(filepath,newfilepath)

Upvotes: 4

Related Questions