python - 重命名python时出现权限错误
问题描述
我想用我的 python 脚本重命名文件和子目录。
简单地替换“。” 带空格。
示例目录树:
.\fsdf.trsd.nf.g
.\beautifyer.py
.\lsWithSdir.py
.\fsdf.trsd.nf.g\fe.gre.asd
.\fsdf.trsd.nf.g\fa.tr.bdtxt
. \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 Traceback(最近一次调用最后):
文件“.\beautifyer.py”,第 41 行,在
get_items(dirPath)
文件“.\beautifyer.py”,第 35 行,在 get_items
checkType(file_path, name)
File ".\beautifyer.py", line 21, in checkType
os.rename(filePath, os.path.join(filePath, new_name))
PermissionError: [WinError 32] The process cannot access the file because it is being used通过另一个过程:'.' -> '.\fsdf trsd nf g'
解决方案
您向 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)
推荐阅读
- android - 从网格 RecyclerView 到 details 活动的共享过渡效果
- python - Python抓取错误MissingSchema:无效的URL
- python - 随机森林多类 Python 不会提高准确性
- php - 从同一个类创建多个对象
- asp.net - 为什么在我定义了密钥后,我的 ASp.NET React 项目中会出现“唯一的“密钥”道具”错误?
- git - 如果存在其他以后的提交,我将 git commit 推送到远程怎么办?
- php - 如何在我的终端上制作正确的 PHP 版本?
- java - H2:计数查询中的重复列名与嵌套查询
- android - ViewPager 中的子编号不一致
- javascript - 如何以某个定义的角度移动对象?