我想用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 Traceback (most recent call last):
File ".\beautifyer.py", line 41, in
get_items(dirPath)
File ".\beautifyer.py", line 35, in 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 by another process: '.' -> '.\fsdf trsd nf g'
您向checkType函数发送了错误的文件路径请参见下面的修改代码:
相关问题 更多 >
编程相关推荐