Python Rename()PermissionError:[WinError 32]?

时间:2016-03-03 03:39:34

标签: python rename

我试图通过在旧文件名之前添加数字来命令目录中的所有文件(例如"Oldfilename"应该命名为"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)

但是我收到了一个错误:

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. 我搜索了rename()的文档,但没有任何帮助。
  2. 另外,我搜索了十几个类似的问题,我知道在我执行重命名功能之前必须打开我要重命名的文件。
  3. 打开我能检测到的文件的唯一可疑行为是' for'循环,但后来我发现foor循环给我的元素是str类型。
  4. 此外,我尝试通过手动设置' src'来重命名上面的文件。并且' dst',它工作得很好。因此文件本身与错误无关。
  5. 所以,我被卡住了。

1 个答案:

答案 0 :(得分:3)

filepath已包含文件名。您想重命名x\file而不是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)