重命名python时出现权限错误

时间:2019-02-13 12:26:15

标签: python operating-system renaming

我想用我的python脚本重命名文件和子目录。
只需替换“。”带有空格。

示例目录树:

  

。\ fsdf.trsd.nf.g
  。\ beautifyer.py
  。\ lsWithSdir.py
  。\ fsdf.trsd.nf.g \ fe.gre.asd
  。\ fsdf.trsd.nf.g \ fa.tr.b.d.txt
  。\ fsdf.trsd.nf.g \ fe.gre.asd \ new.path
  。\ fsdf.trsd.nf.g \ fe.gre.asd \ New.Text.Document.txt

import os
from os.path import isdir

# prompt user for path
dirPath = input("enter path of dir where the files are\n")

# subs = input("do you want to include renaming for subdirectories? (y/n)\n")

# change to path
os.chdir(dirPath)


# replace spaces
def replace_spaces(file_name):
    new_name = file_name.replace(".", " ")
    return new_name

def checkType(filePath, file):
    if os.path.isdir(file):
        new_name = replace_spaces(file)
        os.rename(filePath, os.path.join(filePath , new_name))
    else:
        file_name, file_ext = os.path.splitext(file)
        new_name = replace_spaces(file_name)
        os.rename(filePath, os.path.join(filePath , new_name + file_ext))



def get_items(dirPath):
    for path, subdirs, files in os.walk(dirPath):
        for name in subdirs:
            file_path = os.path.join(path)
            # doStuff(file_path, name)
            print(file_path + " | " + name)
            checkType(file_path, name)
        for name in files:
            file_path = os.path.join(path)
            checkType(file_path, name)


get_items(dirPath) 

错误:

  

。 | fsdf.trsd.nf.g   追溯(最近一次通话):
    
中的文件“。\ beautifyer.py”,第41行       get_items(dirPath)
    在get_items中的文件“。\ beautifyer.py”,第35行,
      checkType(文件路径,名称)
    在checkType中的文件“。\ beautifyer.py”,第21行
      os.rename(filePath,os.path.join(filePath,new_name))
  PermissionError:[WinError 32]该进程无法访问文件,因为该文件正被另一个进程使用:“。” ->'。\ fsdf trsd nf g'

1 个答案:

答案 0 :(得分:0)

您向checkType函数发送了错误的文件路径,请参见修改后的代码,如下所示:

import os
from os.path import isdir

# prompt user for path
dirPath = input("enter path of dir where the files are\n")

# replace spaces
def replace_spaces(file_name):
    new_name = file_name.replace(".", " ")
    return new_name

def checkType(filePath, file):
    if os.path.isdir(filePath):
        new_name = replace_spaces(file)
        os.rename(filePath, os.path.join(os.path.dirname(filePath) , new_name))
    else:
        file_name, file_ext = os.path.splitext(file)
        new_name = replace_spaces(file_name)
        os.rename(filePath, os.path.join(os.path.dirname( filePath) , new_name + file_ext))



def get_items(dirPath):
    for path, subdirs, files in os.walk(dirPath):
        for name in subdirs:
            file_path = os.path.join(path,name)
            # doStuff(file_path, name)
            print(file_path + " | " + name)
            checkType(file_path, name)
        for name in files:
            file_path = os.path.join(path, name)
            checkType(file_path, name)

get_items(dirPath)